mardi 30 juin 2015

MVC manually serializing complex object or model binding

One of the largest issues I run into in MVC is when I attach a complex property (view model) to my model to use on a form. For example, I have a model called Customer.cs. This Customer has ( for simplicity sake ) 1 order at any time. So I give him a property of Customer.Order. The Customer has many other properties defining him as a unique customer. The Order property has a set of unique properties itself. So I’m rolling along, building my Controller, other model values, and finally I start working out my View details.
I start by defining the Form itself.

@using (Html.BeginForm("Customer", "Home", FormMethod.Post, new { @id = "customerForm" })

This form declaration basically tells the View that when a user clicks Submit, everything within this form should be serialized and sent to the Controller. First, I create a view for my main model, Customer.cshtml. It takes in a Customer.cs model.

I create a View specifically for this complex object I’ve created called Order.cshtml. It takes in an Order.cs model (so I can reuse it later on other parent models, such as Invoice because I’m smart and think ahead.) I build my textboxes, dropdown lists, grids, whatever you need it’s there, it’s flashy and it works. So I’ve written all of this javascript and view logic that depends on the view being independent and reusable with other models, etc, etc. My textboxfor declarations look like so:

@Html.TextBoxFor(m => m. OrderDate) 

When I go to click Submit, the first thing I notice is that none of the values from the Order object is posted back. So I sit there and debug and it takes a while but I finally figure out that this will not work this way. Unless there’s a way to serialize the view model separately, then attach it to the parent model, even then you’d have to write a bunch of Javascript to manually override the default form submission process, along with any other model submits you may be making for client-side field validation.
I think there should be an easier way to handle this. I know a way around this issue, but it’s not pretty. You ‘could’ create the view for Order.cs to take in a Customer.cs model instead. Then, use textboxfor declarations like so:

@Html.TextBoxFor(m => m.Order.OrderDate) 

To define all of the properties on the View. This will work with the default binding and all is well. Except, what about the code I’ve already written in JavaScript? I’d have to go through and append “Order_” to all of the references to ID’s laid out on the form. Also, this does not move easily between models now, I’d have to recreate this View each time I create a new model that uses the Order object, since it now takes in the Customer.cs model. I’d also have to rewrite the javascript, or come up with some fancy way to pass in a prefix (ViewData). This doesn’t seem correct. What am I doing wrong?

Setting the Culture per request is impossible in ASP.NET

Setting the culture settings per request should be easy, right? Well it isn't because you set the culture settings on a thread not a request and apparently ASP.NET doesn't always execute the whole request on a single thread. Sure I could use DefaultThreadCurrentCulture, but that would set the culture on all threads, not just the ones used by the specific request.

So am I missing something here or what? Because when I set the culture in Global.asax's Application_AcquireRequestState() function (so it executes once at the beginning of each request) for some reason I have property display names popping up in multiple languages and when I dug deeper, I found out that in the Display Name Attribute's constructor the CurrentCulture and CurrentUICulture settings are sometimes completely different from what I set in Global.asax.

I'm sure that the problem isn't in my customized display name attribute, but you can see it below anyway:

public class DDisplayName : DisplayNameAttribute
    {
        public DDisplayName(string resourceId)
            : base(GetAttributeName(resourceId))
        {  }

        private static string GetAttributeName(string resourceId)
        {
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.LCID + "|" + System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;

            ResourceManager resMan = new ResourceManager(typeof(Strings));

            string result = resMan.GetString(resourceId);

            return result == null ? "Resource string: " + resourceId + " not found" : result+" "+lang;

        }
    }

As you can see I even added the LCIDs do the display name so I can see them on the screen, and the Culture Settings are different.

lundi 29 juin 2015

This page can’t be displayed - Asp.Net MVC3 on IIS 8.5 Windows Server 2012

I have an MVC 3 application and WCF service to be deployed in IIS 8.5 installed on Windows Server. I have checked all the prerequisites installed for IIS 8.5. After the deployment when I try to access the .svc files, I get "This page can't be displayed". The have verified the below conditions.

APP POOL:

1.) The app pool is set to "Integrated" mode and targetted to V4.0.

2.) Identity is set to "ApplicationPoolIdentity" and enabled 32 bit applications.

BINDINGS:

1.) Provided a different port"88" and ip address is configured.

PERMISSIONS:

1.) Full access has been provided for the below mentioned users.

a.) IUSR

b.) IIS_IUSRS

c.) DefaultAppPool(This is the app pool that has been assigned).

I am struck with this, Please let me know for anything that needs to be included.

Is there a real need in an Anti-XSS in web forms today

Well, my company have a webs site which contains 5 pages of web forms and 2 mvc,

and we were thinking to put the (Microsoft AntiXSS / Web protection) which should protect agiest XSS, but then iv'e read that its a part of the .net 4.5, which means i don't need to put anything to protect myself agiesnt XSS?

In out code behind we check every text box that comes to the server(If its need to be int, then its check to int, if guid, checked to guid). is there any real need to another thing to protect?

Thanks so much.!

dimanche 28 juin 2015

Custom routehandler not working in mvc3

Hi i want to make a custom route handler. its saying the resource cannot be found. here is my code in global.ascx

routes.Add(new Route("Key/{id}-{type}.jpg", new RouteKeyHandler()));

and RouteKeyHandler code

  public class RouteKeyHandler:IRouteHandler
{ 
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        RouteKeyHandler httpHandler = new RouteKeyHandler();
        return httpHandler;
    }   
    public class RouteKeyHandler : IHttpHandler
    {  
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var routeValues = context.Request.RequestContext.RouteData.Values;               
        } 
    }
}

when i set url to localhost/Key/17-news.jpg it gives error

The resource cannot be found.

samedi 27 juin 2015

How to close inactive connections in Postgres

Postgres 9.1 sever is running under Debian. It is accessed by Mono MVC4 web applications using ngpsql, Apache and mod_mono. It is also accessed by pg_dump in same computer every night and from 5432 port from internet. Connections were cleared at June 20. pgAdmin statuc window shows lot of idle connections starting from this day. (see image below).

After some time number of connections goes to 100 and server stops to accept connections. Connections needs to be manually killed in pgAdmin. Only after that server start accepting connections again.

It is interesting that start times of some of those connections are exactly the same as shown in image. How to fix or diagnose the issue ? I tried /etc/init.d/apache2 restart . This closed 25 and 27 June connections but 20 June connections are still open.

How to close idle connections automatically or find the reason of open connections ? Maybe there is some postgres or Debian setting which closes idle connections automatically ?

open connections

Using

"PostgreSQL 9.1.2 on x86_64-unknown-linux-gnu, compiled by gcc-4.4.real (Debian 4.4.5-8) 4.4.5, 64-bit"

vendredi 26 juin 2015

Get value of an input c# mvc

hello i have input boxes which i need to get a value of cause later i will redirect them to a specific controller and i dont know how to access there values

 <form action="@Url.Action("AddSpecific", "Comment", new { AuthorT ="1", WebSiteT = "1", postIdT = 1, TextT = "1",TitleT = "1" })" method="post">

<h1>
    <label for="Title">Title</label>
    <input name="Title" id="Title" type="text"  required />
</h1>
<h1>
    <label for="Text">Text</label>
    <input name="Text" id="Text" type="text" required />
</h1>
<h1>
    <label for="AuthorSite">AuthorSite</label>
    <input name="AuthorSite" id="AuthorSite" required />
</h1>
<h1>
    <label for="Author">Author</label>
    <input name="Author" id="Author" type="text" required />
</h1>
<h1>a
    <label for="IdOfPost">IdOfPost</label>
    <input name="IdOfPost" id="IdOfPost" type="number" required />
</h1>

<input type="submit" value="Post comment" />

Thank you very much

Adding an item to a table in MVC

I have created a table of comments and in a separate view I want to add comments.

I made this code in that view:

<form action="#" method="post">
    <h3>Post a comment</h3>
    <h1>
        <label for="Title">Title</label>
        <input name="Title" id="Title" type="text" required />
    </h1>
    <h1>
        <label for="Text">Text</label>
        <input name="Text" id="Text" type="text" required />
    </h1>
    <h1>
        <label for="AuthorSite">AuthorSite</label>
        <input name="AuthorSite" id="AuthorSite" required />
    </h1>
    <h1>
        <label for="Author">Author</label>
        <input name="Author" id="Author" type="text" required/>
    </h1>
    <input type="submit" value="Post comment" onclick=""@Url.Action("Index", "Home")"/>
</form>

I have no idea what to do in the button when I want to add that information to the table.

Delete File in SharePoint folder using C#

I am using SharePoint ExcelService to manipulate an excel file and then save it to the Shared Documents folder using

ExcelService.SaveWorkbookCopy()


Now I want to delete those files I saved earlier. What is the best way to achieve this using C# in a Asp.Net MVC Application?

I tried it using the REST Service, but I could not really find any tutorials and as the code is now, I get a WebException "The remote server returned an error: (403) Forbidden." I tried two versions for my REST URL, neither worked.

var fileSavePath = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/Shared%20Documents/";
var excelRestPath_1 = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/_api/web/";
var excelRestPath_2 = "http://sharepointserver/_api/web/";

    public static bool DeleteExcelFromSharepoint(int id, string excelRestPath)
    {
        try
        {
            string filePath = "/Shared%20Documents/" + id + ".xlsm";
            string url = excelRestPath + "GetFileByServerRelativeUrl('" + filePath + "')";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "DELETE";
            request.Headers.Add(HttpRequestHeader.IfMatch, "*");
            request.Headers.Add("X-HTTP-Method", "DELETE");

            request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException(String.Format("DELETE failed. Received HTTP {0}", response.StatusCode));
                }
                return true;
            }

        }
        catch (Exception ex)
        {
            CustomLogger.Error("Error deleting Excel from Sharepoint", ex);
            return false;
        }
    }

Dot matrix Print integration in asp.net mvc3

I am trying to develop a school's software using asp.net mvc 3. My problem is that I want to integrate dot matrix print for showing the receipt and I have no idea to do.

jeudi 25 juin 2015

How to rename "browse" button in Html.TextBoxFor

I can rename it in a aspx File using an extra Button and a Javascript method that puts the button in front of the FileUpload.

but how to achive the same in a MVC View:

@Html.TextBoxFor(m => m, new { @class = "form-control", type = "file" })

Folder Browser Dialog in ASP.net

I'm looking for Folder Browser Dialog in asp.net like winform FolderBrowserDialog

DialogResult result = folderBrowserDialog1.ShowDialog();

But there is no future in ASP.net. By the way I'm not looking Treeview list because user have to select folder from drive or network.

So is it possible to run winform in webpage? Could you give me an example ?

MVC3 & Ajax : Refresh list to hide a record which was deleted from list by a button click

I have a list which displays Subscribed forums threads and with in each row there is a button to un-subscribe. I works fine using Ajax to unsubscribe, but I want to refresh using Ajax to remove unsubscribed thread from the list. Can anyone please suggest me. My code is as below:

Idea behind using Ajax is because I just want to refresh the list section not entire page.

Index.aspx

<% foreach (var thread in Model.threads) { %>
    <tr>
        <td><%: thread.Title %></td>
        <td><%: Ajax.ActionLink("Unsubscribe", "ToggleForumAlertFromList",
                    new { id = thread.ForumId },
                    new AjaxOptions { HttpMethod = "POST", 
                        UpdateTargetId = "none", 
                    new { ID = "togglealertlink" })%>
        </td> 
    </tr>
<% } %>       

Controller

[HttpPost]
public ActionResult ToggleThreadAlertFromList(Guid id)
{
    // Do stuff to unsubscribe        
    return new EmptyResult();
}

open a new window form action method in MVC

I am trying to open a url from the javascript function.

The issue is I am not able to authorize it the url mentioned in the image.

How can I load the page from the action method so that i can authorize the url.

Here is my Javascript method.

<img src="~/Images/question_frame.png" style="margin-top:3px;height:18px;width:20px;" onclick="window.open('../help/nmc/enu/default.htm', 'NMCHelp', 'toolbar=no, scrollbars=yes, resizable=yes, top=50, left=50, width=750, height=600');"/>

How can i achieve this?

How do i get the window.open(.../help/nmc/enu/default.htm) to opened from the action method in a new window so that when anyone tried to open the window with out authorized will be redirected to login page.

Managing ViewBag state from controller, view, partial views & layout

I'm not understanding how ViewBag state is managed between the controller, view, partial views, _ViewStart and layouts.

In particular, in _ViewStart.cshtml I set

@{
      Layout = "~/Views/Shared/_Layout.cshtml";
      ViewContext.ViewBag.Title = "Default Title";
}

Yet, in _Layout.cshtml the

ViewBag.Title is not defined

Should it not be defined?

A required anti-forgery token was not supplied or was invalid when trying to log in same user in different tab

In mvc2 application I have used Antiforgery token in login page.Problem is when a user is logged in and opens another tab enters same credentials for login , it is throwing an error "A required anti-forgery token was not supplied or was invalid." If i remove it is working fine. Help me to fix this issue.

mercredi 24 juin 2015

Rotativa.BuildPdf() Causing Access Denied Error

I am trying to save a generated PDF via the BuildPdf() method, so I can save the PDF to a database. I am testing the code below, by running locally in Visual Studio 2013 running IIS Express.

I have scoured the web for solutions, including the Rotativa page on GitHub but to no avail. Perhaps someone else has run into this same issue?

BTW, I get "Access Denied" when running from command line, too:

wkhtmltopdf.exe README.txt test.pdf

I read that a missing C++ dll can cause this error so I checked and I have the file installed, found here:

http://ift.tt/1HeTgXp

Thanks

Here is my link for generating the PDF binary

   <a id="email-me" class="btn icon print"
     href='@Request.Url.GetLeftPart(UriPartial.Authority)@Url.Action("SaveMyViewToDb", "Report",
                         new
                             {
                                 id = 68073,
                                 clubKeyNo = "K10158",
                                 month = 12,
                                 year = 2014
                             }, null)'>@ViewReport.PrintReport</a>

Here is the Action

    public JsonResult SaveMyViewToDb(int? id, string clubKeyNo, int month, int year)
    {

        string fileName = "MyReport";
        var pdfResult = new ActionAsPdf("ViewReport", new { id = id, 
                                                            clubKeyNo = clubKeyNo, 
                                                            month = month, 
                                                            year = year, printMode = true }) 
                                                            { FileName =  fileName + ".pdf" };

        var binary = pdfResult.BuildPdf(this.ControllerContext);

        var saveResult = ReportingDBTasks.SaveDownloadableFileToDb(binary, "pdf", fileName, PersonifyTasks.GetPrimaryEmailString(TaskBase.MasterCustomerId));


       return Json((saveResult ? "Success: Your file is being generated. We will email you once it's ready." : "Error: We were unable to grant your request."));
    }

Here is the stack trace

[Win32Exception (0x80004005): Access is denied] System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) +1789 System.Diagnostics.Process.Start() +6814726 Rotativa.WkhtmltopdfDriver.Convert(String wkhtmltopdfPath, String switches, String html) +459 Rotativa.WkhtmltopdfDriver.Convert(String wkhtmltopdfPath, String switches) +63 Rotativa.AsPdfResultBase.CallTheDriver(ControllerContext context) +102 Rotativa.AsPdfResultBase.BuildPdf(ControllerContext context) +250 Reporting.Controllers.ReportController.SaveMyViewToDb(Nullable1 id, String clubKeyNo, Int32 month, Int32 year) in c:\GitProjects\kiwanisonereporting\Reporting\Controllers\ReportController.cs:1003 lambda_method(Closure , ControllerBase , Object[] ) +335 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +211 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +253 System.Web.Mvc.<>c__DisplayClass17.b__14() +21 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +189 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324 System.Web.Mvc.Controller.ExecuteCore() +105 Reporting.Controllers.BaseController.ExecuteCore() in c:\GitProjects\reporting\Reporting\Controllers\BaseController.cs:40 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +90 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.b__5() +34 System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +19 System.Web.Mvc.Async.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +10 System.Web.Mvc.Async.WrappedAsyncResult1.End() +62 System.Web.Mvc.<>c__DisplayClasse.b__d() +48 System.Web.Mvc.SecurityUtil.b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651796 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

how to restrict keyboard input on @Html.ValidationMessageFor(model => model.currentctc, "", new { @class = "text-danger" })

//how to stop the user for entering character or number in Textbox this is mvc application so I use MVC model validation

The type or namespace name 'ModelStateDictionary' could not be found

I did just upgrade a asp.net mvc2 project to mvc3 with this tool. http://ift.tt/1cNJ7Te And that did work rather well,

how ever now I ran into an issue with the MVC3 project I have two error that states this: The type or namespace name 'ModelStateDictionary' could not be found.

Even though I am using System.Web.Mvc

enter image description here

How to mix javascript with razor code

What the syntax to add the following javascript within my razor (chtml) template?

<script type="text/javascript">

 $(function(){ 
    @if(Model.IsModalShown)
    {
        $('#myModal').modal('show');
    }
 });

</script>

mardi 23 juin 2015

Not able to convert string to decimal in mvc

Hi i am working on a MVC project where i stuck on very small issue.I have Item price which is coming in decimal and i also decalred it as decimal.

it all works fine.Price displays perfectly the way i want.

Now the problem is that i dont want to display the price if user is not loged in.

Now the problem is that ITEM.PRICE COMES LIKE 32.5D

But if user not loged in then i want to display blank here.

I am trying something like this but its not working:

  @If Session("UserData") Is Nothing Then


           item.Price=Decimal.Parse("")                          

   End if

How to get number of invoices for last 12 weeks in Postgres

Invoice database contains invoice dates:

create table dok (
  dokumnr serial primary key,
  invoicedate date not null
);

Dashboard requires comma separated list containing number of invoices for last 12 weeks, e.q

4,8,0,6,7,6,0,6,0,4,5,6

List contains always 12 elements. If there are no invoices for some 7 day interval, 0 should appear. Every element should contain number of invoices for 7 days.

Query should find maximum date before current date:

select max(invoicedate) as last_date from dok;

And after that probably use count(*) and string_agg() to create list.

Last (12th) element should contain number of invoices for

  last_date .. last_date-interval'6days'

11 element (one before last) should contain number of invoices for days

  last_date-interval'7days' .. last_date-interval'14days'

etc.

How to write this query in Postgres 9.1+ ? This is ASP.NET MVC3 C# application and some parts of query can also done in C# code if this helps.

I ended with

with list as (

SELECT count(d.invoicedate) as cnt
   FROM  (
      SELECT max(invoicedate) AS last_date
      FROM   dok
      WHERE   invoicedate< current_date
      ) l
   CROSS  JOIN generate_series(0, 11*7, 7) AS g(days)
   LEFT   JOIN dok d ON d.invoicedate>  l.last_date - g.days - 7
                    AND d.invoicedate<= l.last_date - g.days
   GROUP  BY g.days
   ORDER  BY g.days desc
)

SELECT string_agg( cnt::text,',')
from list

Get content of cells on same row

I have an issue very similar to what was asked on enter link description here, but the syntax is a little different. I'm pretty sure it's a minor tweak but have spent too much time trying. Any help would be appreciated.

I am trying to pass the contents of selected row cells from a Telerik GV. The "path" variable is passed through a partial view, I cannot use "this" as it is not run directly from a click event. My issue is the var t3 returns the concatenated contents of ALL the rows contents for that column : "Test Deschi ho hi whatevah". How can I modify this to only give me the cell contents of the row with the matching span id? Thank you in advance.

<tr>
 <td><input id="..." value="Accounting-Payroll" type="checkbox"></td>
 <td><span id="Accounting-Payroll_span">Accounting-Payroll</span></td>
 <td></td>
 <td>Test Desc</td>
</tr>
<tr>
 <td><input value="Advertising and Marketing" type="checkbox"></td>
 <td><span id="Advertising and Marketing_span">Advertising and Marketing</span></td>
 <td></td>
 <td></td>
</tr>
<tr>
 <td><input id="..." value="TestAccessFile600.pdf" type="checkbox"></td>
 <td><span id="TestAccessFile600.pdf_span" style="padding-left: 2px;"> TestAccessFile600.pdf</span></td>
 <td>Title for test access file yada</td>
 <td>hi ho hi whatevah</td>
</tr>

    var path='TestAccessFile600.pdf';

    function EditFile(path) {
    var trw = $("td").filter(function () {
        return  $('span#' + path + '_span')}).closest("tr");
    var t3 = trw.find('td:eq(3)').text();
    ...
}

Lambda, how to sum and count?

namespace PJ.Domain.Entities
{
    [Table("test")]
    public class Test
    {
        [Key]
        public int id {get; set;}
        public child_1_id {get; set;}
        public child_2_id {get; set;}
        public string f_name{get; set;}
        public string l_name{get; set;}

        [ForeignKey("child_1_id")]        
        public virtual ICollection<Child1> child1 { get; set; }

        [ForeignKey("child_2_id")]        
        public virtual ICollection<Child2> child2 { get; set; }

    }
}

// Controller

IQueryable<Test> TestQuery = unitOfWork.TestRepository.getDbSet();

var items = (from i in TestQuery
                select new
                {
                    fName = i.f_name,
                    lName = i.l_name,
                    child1Cnt = //! child1 count(x.id)
                    child2Sum = //! child2 sum(x.age)

how to count and sum for child1 and child2?

MVC how to return a view with a parameter in mvc5

I would like have the same effect with but returning the View from the Controller, at the moment I'm using this code with no success

How to separate controller to outside project in Case of MVC Area

I have an requirement where i need to separate controller outside the MVC project. My situation is like i am having 3 areas inside the MVC project and i have take out all controller inside each area into separate project by keeping all the view inside the area. I have no idea how to achieve this. If any one came across this or implemented please share your tots and codes.

Thanks.

How to get started with Visual studio 2012

I want to create web application using Visual Studio 2012. The application should login into a website and report numerical findings on the UI.

The language used will be Visual C#.

I have loaded the application and selected on the menu: File> New > Projects.

A window appears with multiple options. I am starting to learn about programming language such as C# and Visual Basic.

"New project" window appearing

Would I be able to have a bit of help on this.

Thank you :)

lundi 22 juin 2015

CRUD operation in a single view in ASP.Net MVC

Im trying to create a simple asp crud application but i dont want to create servral views.This is how i do it:

i have a view named index and a controller named HomeController

public class HomeController : Controller
{
    private readonly InventoryContext _db = new InventoryContext();
    public ActionResult Index()
    {  
        return View();
    }


    [HttpPost]
    public ActionResult Create()
    {
        //ItemType is a class
        var itemType = new ItemType { IsBarCode = true, ItemTypeName = "fsdfadfadf" ;
        return View("Index",itemType);
    }

    [HttpPost]
    public ActionResult Save()
    {
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
}

}

and i view i bind my buttons to controller actions:

<input type="submit" value="Create" onclick="location.href='@Url.Action("Create", "Home")'"  class="button btn btn-default" />

<input type="submit" value="Save" onclick="location.href='@Url.Action("Save", "Home")'" class="button btn btn-success" />

The problem is the Create action look for /Home/Create view after user submit data too server using httppost,but i want to redirect it to same view that called it(index view here).

samedi 20 juin 2015

code execute but not reviving mail in inbox c#

i have write code for sending email but code executes succefull but mail is not receiving inbox.plzz help me and correct code where is mistake or why not receiving mail.below of my code see my code and tell me what is problem that is not sending mail. i m working on project in which forget password and username send to user who enter email ID.

protected void Button2_Click(object sender, EventArgs e) {

        string email = TextBox1.Text;
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=regester;Integrated Security=True");
        string command = "select id,password,email from reg ";
        SqlCommand sqlcmd = new SqlCommand(command, con);
        //sqlcmd.Parameters["@Email"].Value = email;
        //sqlcmd.Parameters.Add("@Email", email);
        con.Open();
        if (con.State == ConnectionState.Open)
        {
            SqlDataReader dtr = sqlcmd.ExecuteReader();

            while (dtr.Read())
            {
                if (dtr[2].ToString().Equals(TextBox1.Text))
                {
                    MailMessage mail = new MailMessage();
                    mail.To.Add(dtr[2].ToString());
                    mail.From = new MailAddress("mian722@hotmail.com");
                    mail.Subject = "Your userId and Password";
                    mail.Body = "Your<br/> UserId:<b>" + dtr[0].ToString() + "</b><br/>" + "Password:<b>" + dtr[1].ToString() + "</b>";
                    mail.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;

                    smtp.Credentials = new System.Net.NetworkCredential("your id", "your password");
                    smtp.EnableSsl = true;
                    //smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    //smtp.EnableSsl = true;
                    //smtp.UseDefaultCredentials = true;
                    smtp.EnableSsl = true; //Gmail works on Server Secured Layer
                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception ex)
                    {

                    }  
                    //smtp.Send(mail);

                    Label1.Text = "check your mailbox for user iD and Password";

                    string javaScript = "<script language=JavaScript>\n" + "alert('User Id and password send to Your mail box');\n" + "</script>";
                    RegisterStartupScript("xyz", javaScript);
                    break;
                }
                else
                {
                    Label1.Text = "Email Id not valid";
                }

            }

How to store php form data to a web server in a plain text file?

I have an assignment that calls for data entries from a php form to be stored in a plain text file on the same web server. I created the php form page and the plain text file but I am unsure how to connect the two. I've searched the internet and tried multiple ways for about two hours now and no dice. The data entries have to accumulate in the plain text file too (1st person submits, and a 2nd person submitting can see 1st person's submission and so on).

I didn't add any of the code I've tried to the plain text file because none of them were working and I wanted to (in theory) simplify the process of not having to try and fix the code. I know that the plain text file needs some sort of code to retrieve the code from the php form but unsure what to try at this point. And yes I wrote permissions for the plain text file to be writable via FileZilla.

Here's my php form code:

<!DOCTYPE HTML> 
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 

<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $likesErr = $howErr = $rateErr = "";
$name = $email = $comment = $likes = $how = $rate = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
 $nameErr = "Name is required";
} else {
 $name = test_input($_POST["name"]);
}


$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format"; 
}

if (empty($_POST["comment"])) {
 $commentErr = "Comments are required";
} else {
 $comment = test_input($_POST["comment"]);
}

if (empty($_POST["likes"])) {
 $likesErr = "Things you liked is required";
} else {
 $likes = test_input($_POST["likes"]);
}

if (empty($_POST["how"])) {
 $howErr = "How you got to our site is required";
} else {
 $how = test_input($_POST["how"]);
}

 if (empty($_POST["rate"])) {
 $rateErr = "Rating our site is required";
} else {
 $rate = test_input($_POST["rate"]);
}
}

function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
     .removeAttr('checked').removeAttr('selected');
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> 

<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>

E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>

Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>

How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>

Rate our site:
<select name="rate">
<option value="">- Please Select -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>

<input type="submit" name="submit" value="Submit"> 
<input type="reset" value="Reset">

</form>

</body>
</html>

And here's the plain text file code:

<!DOCTYPE html>
<html>
<head>
    <title>Roy Feedback Results Assignment 7</title>
</head>
<body>



</body>
</html>

vendredi 19 juin 2015

Is there a way to make the security settings in PDFSharp work in an environment that is restricting to FIPS compliant algorithms?

I am using PDFSharp with a C# MVC3 application to generate a PDF for completing a survey. Everything was working fine until we recently migrated to a Windows Server 2008 environment with the setting "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing" enabled.

Has anyone found a way to continue setting security settings on the PDF while in this type of environment? Here is the security setting block of code that if I remove everything will work:

PdfSecuritySettings securitySettings = pdfDocument.SecuritySettings;
securitySettings.OwnerPassword = "owner";

// Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = false;
securitySettings.PermitModifyDocument = false;
securitySettings.PermitPrint = true;
securitySettings.PermitFullQualityPrint = true;

Any thoughts? I was thinking of pulling down the PDFSharp source and seeing if I could use a different algorithm because I believe the issue is with the MD5CryptoServiceProvider.

jeudi 18 juin 2015

Redirect returns "Object moved to"

I have a problem. When I try to redirect user to non-http URL from MVC action, it returns:

Object moved to here.

Full response (from Fiddler):

HTTP/1.1 301 Moved Permanently
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: myGame-app://test.somespecificdata
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUGlvdHJcRGVza3RvcFxUYWtlc0NhcmVcVGFrZXNDYXJlXERvY3RvcnNcRWRvY3RvclxDb25zdWx0YXRpb25cMTkx?=
X-Powered-By: ASP.NET
Date: Thu, 18 Jun 2015 18:19:35 GMT
Content-Length: 457

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="myGame-app%3a%2f%2ftestprotocol.somespecificdata">here</a>.</h2>

<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
    {"appName":"Firefox"}
</script>
<script type="text/javascript" src="http://localhost:53098/4c9c75263d91451fa797f9041e4bd0f3/browserLink" async="async"></script>
<!-- End Browser Link -->

</body></html>

My action (with pseudo code):

[HttpGet]
public ActionResult Consultation(int id)
{
      //.. specific business logic
      if(IsMobile()){
          return RedirectPermanent("myGame-app://test.somespecificdata"); 
      }
      else{
          return View("AboutGame", SomeSpecificModel);
      }
}

The same situation is with return Redirect() instead of return RedirectPermanent().

My main goal is to redirect a user who uses the mobile browser to URL with special protocol (not http). This special protocol (myGame-app://) runs my mobile app according to this Stack discussion. How can I achieve this, without information Object moved to here?

Regards

How to improve dll loading time .net

I've created a dll and its size is 4 mb. The issue is when I call the dll it is taking 6 - 7 sec. Anybody has same issue. please suggest any solution.

Thanks for your suggestion.

The Google reCAPTCHA doesn't work with ASPX

I try to make a recaptcha system on my ASPX form and i can use asp:CustomValidator for all the fields and they show me the errors messages (required or incorrect) but it's not the case for the asp:CustomValidator of recaptcha:

Here is a part of my form page:

<div style="display: inline-table; width: 100%;padding-left:3%;">
      <asp:Label ID="Label1" runat="server" Text="Number of phone " CssClass="text"></asp:Label>
      <b class="te_red">* </b>                             
      <asp:TextBox ID="Tb_Li" runat="server" CssClass="log_tb" MaxLength="10"></asp:TextBox>
      <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Can you make a number phone." Display="None" ControlToValidate="Tb_Li" OnServerValidate="cv_validate_nPhone" ValidateEmptyText="true" ValidationGroup="mugroupValid"></asp:CustomValidator>
</div>
<script type="text/javascript" src="http://ift.tt/1yW6XBL"
async defer></script>
<script type="text/javascript">
    var onloadCallback = function () {
         grecaptcha.render('dvCaptcha', {
         'sitekey': '<%=ReCaptcha_Key %>',
         'callback': function (response) {
         $.ajax({
         type: "POST",
         url: "http://ift.tt/1Im50Sw",
         data: "{response: '" + response + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (r) {
         var captchaResponse = jQuery.parseJSON(r.d);
         if (captchaResponse.success) {
               $("[id*=txtCaptcha]").val(captchaResponse.success);
               $("[id*=rfvCaptcha]").hide();
         } else {
               $("[id*=txtCaptcha]").val("");
               $("[id*=rfvCaptcha]").show();
               var error = captchaResponse["error-codes"][0];
               $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
         }
        }
       });
      }
     });
    };
  </script>
  <div id="dvCaptcha">
  </div>
  <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<asp:CustomValidator ID="rfvCaptcha" runat="server" ErrorMessage="Veuillez cocher la case que vous n'êtes pas un robo." 
                                    Display="None" ControlToValidate="Tb_Ligne"  ValidateEmptyText="true" OnServerValidate="cv_validate_captcha" ValidationGroup="mugroupValid"></asp:CustomValidator>
<asp:LinkButton ID="btn_validate" runat="server" Text="Validate"   OnClick="btn_validate_Click" ValidationGroup="mugroupValid" CausesValidation="true" />

This is a part of the code of my ContacForm.aspx.cs:

public partial class ContacForm: System.Web.UI.Page
{
protected static string ReCaptcha_Key = "<RECaptcha Site Key>";
protected static string ReCaptcha_Secret = "<RECaptcha Secret Key>";

[WebMethod]
public static string VerifyCaptcha(string response)
 {
    string url = "http://ift.tt/1vh5G4o" + ReCaptcha_Secret + "&response=" + response;
    return (new WebClient()).DownloadString(url);
 }


protected void cv_validate_captcha(object sender, ServerValidateEventArgs e)
    {

        e.IsValid = txtCaptcha.Text.ToString().Length > 0;

    }

protected void cv_validate_nPhone(object sender, ServerValidateEventArgs e)
    {
        Regex myRegex = new Regex(@"[0-9]{10}$");
        e.IsValid = myRegex.IsMatch(e.Value.ToString());
    }
}

When I completed the form without filling fields that does not pass by telling me that I have to fill everything and when I make them without checking the box of the captcha the form passes while as a rule that has to not pass

mercredi 17 juin 2015

MVC3 Dropdown list and Bootstrap Modal does select the server value of the list

Well, im using .Net MVC3 with razor and the modals from bootstrap to make a web page.

This is my view:

Clientes: @Html.DropDownList("Clientes", new SelectList(Datamodel.GestorDatos.ConjuntoClientes.ListarClientesStatic(), "Codigo", "Empresa", 24), new {@class = "form-control chosen", id = "Clientes" })

I'm sending from the server two objects one with the primary key 23 and another with the primary key 24 those two objects are in a "IEnumerable" object. I don't know why with the modal always choose me the 23 value as default.

How to get number of invoices for last 12 weeks in Postgres

Invoice database contains invoice dates:

create table dok (
  dokumnr serial primary key,
  invoicedate date not null
);

Dashboard requires comma separated list containing number of invoices for last 12 weeks, e.q

4,8,0,6,7,6,0,6,0,4,5,6

List contains always 12 elements. If there are no invoices for some 7 day interval, 0 should appear. Every element should contain number of invoices for 7 days.

Query should find maximum date before current date:

select max(invoicedate) as last_date
  from dok ;

And after that probably use count(*) and string_agg() to create list.

Last (12th) element should contain number of invoices for

  last_date .. last_date-interval'6days'

11 element (one before last) should contain number of invoices for days

  last_date-interval'7days' .. last_date-interval'14days'

etc.

How to write this query in Postgres 9.1+ ? This is ASP.NET MVC3 C# application and some parts of query can also done in C# code if this helps.

returning variable from EndInvoke

I have a method that runs in it's own thread via BeginInvoke.

caller.BeginInvoke(pId, sID.Value, pi, vIRB, a, sls, aspNetUserID.Value, pbID, CreateComplete, caller);

The CreateComplete method is the callback it does after it's done.

    private void CreateComplete(IAsyncResult result)
    {
        Caller caller = (Caller)result.AsyncState;
        string fileName = caller.EndInvoke(result);
    }

It generates a file that needs to be downloaded. Before I threaded things I returned the file path to javascript and had it open a window to that location to download the file.

I tried storing it as a Session variable, passing the HTTPContext.Current to the BeginInvoke method, but that is null when it arrives.

How can I save the returned file path so that I can do something similar in the new threaded system.

Inherited Property of Model is always returning Null Value

I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window.

The problem is that the property named 'ReportName' always return a Null value when submit button is pressed instead of the returning a string value of selected Radiobutton Other properties such as Branchcode, PeriodFrom, PeriodTo return correctly.

what should i do to get proper string value such as AppointmentSummary, SplcodeRegSummary, or SplcodeReg when its radiobutton is selected.

Thanks in advance for your help.

MODEL:

public class ReportModel
{
    [Required(ErrorMessage = "Please select a Report!")]
    public string ReportName { get; set; }
}

public class ReportFilters :ReportModel         //inherited 
{
    [Required(ErrorMessage="Please select Branch name!")]
    public int BranchCode { get; set; }

    [Required(ErrorMessage = "Please specify 'Period from' date!")]
    [DataType(DataType.Date)]
    public DateTime PeriodFrom { get; set; }

    [Required(ErrorMessage = "Please specify 'Period to' date!")]
    [DataType(DataType.Date)]
    public DateTime PeriodTo { get; set; }
}

CONTROLLER:

public ActionResult MIS1()
{
    ViewBag.Branch = (from c in BranchList().AsEnumerable()
                      orderby c["BranchName"]
                      select new { BranchCode = c["BranchCode"], BranchName = c["BranchName"] }).ToList();

    return PartialView();
}


public ActionResult MISPopup(ReportFilters rf)
{
    if (ModelState.IsValid)
    {
        return View(rf);
    }
    return View();
}

VIEW:

<TABLE>
<TR>
<td>
    @Html.RadioButtonFor(model => model.ReportName, "AppointmentSummary", new { id = "AppointmentSummary" })
    @Html.Label("AppointmentSummary", "Appointment Summary")<br />

    @Html.RadioButtonFor(model => model.ReportName, "SplcodeRegSummary", new { id = "SplcodeRegSummary" })
    @Html.Label("SplcodeRegSummary", "Special codewise Registration summary")<br />

    @Html.RadioButtonFor(model => model.ReportName, "SplcodeReg", new { id = "SplcodeReg" })
    @Html.Label("SplcodeReg", "Special codewise Registrations")<br />
</TD>
</TR>

<TR>
<TD>
    @Html.Partial("~/Views/Shared/ReportFilters.cshtml")
</TD>
</TR>
</TABLE>

PARTIAL VIEW:

@model MVCProject.Models.ReportFilters
@using (Html.BeginForm("MISPopup", "MIS", FormMethod.Get, new { target = "_blank" }))
{ 
<div >
    <table width="100%">
        <tr>
            <td>
                @Html.HiddenFor(model => model.ReportName)
                @Html.Label("ClinicBranch", "Clinic Branch")
            </td>
            <td colspan="3">
                @try
                {
                    @Html.DropDownListFor(model => model.BranchCode, new SelectList(ViewBag.Branch, "BranchCode", "BranchName"), "--Select Branch--")
                }
                catch (Exception e)
                {
                    @Html.DropDownList("Branch", new SelectList(string.Empty, "Value", "Text"), "--Select Branch--")
                }
                @Html.ValidationMessageFor(model => model.BranchCode)
            </td>
        </tr>

        <tr>
            <td>
                @Html.Label("FromDate", "From date")
            </td>
            <td>
                @Html.EditorFor(model => model.PeriodFrom)
                @Html.ValidationMessageFor(model => model.PeriodFrom)
            </td>
            <td>
                @Html.Label("ToDate", "To date")
            </td>
            <td>
                @Html.EditorFor(model => model.PeriodTo)
                @Html.ValidationMessageFor(model => model.PeriodTo)
            </td>
        <tr><td colspan="4"><br /></td></tr>
        <tr>
            <td colspan="4" style="text-align:center;">
                <input type="image" id="submit" value="View"  src="~/Images/View.png" />
            </td>
        </tr>
    </table>
</div>
}

Data is not for 2nd time saving when first time it throws an exception

Following is the code segment I used to save two objects to same data.here Comment field is mandotary field.and the DataContext object instance is intilialized in the constructor of the class. When I give comment field as "NULL" for the Obj1 saving both objects are failing but when I give Obj1.Comment="somthing" and Obj2.Comment=NULL the first one is save to the database. I can avoid this declaring a new data context inside the "SaveObj" method.But I want to know why is this happening.does this DataContext going to an error state ? Does any one has idea the reason to happen to this

 public bool SaveObjectList(exemp List)
    {
        try
        {
            SaveObject(List.object1);
            SaveObject(List.object2);
        }
        catch
        {
            return false; 
        }
        return true;
    }

   public bool SaveObject(Exemp object)
   {  
          try{
                Table newObj = new Table()
                {
                    Id = Guid.NewGuid(),
                    Comment = exemption.Comment
                };
                newContext.Table.InsertOnSubmit(newObj);                                                                           
                newContext.SubmitChanges();
            }
         catch{
            return false;
            }
      return true;
    }

mardi 16 juin 2015

Is it possible to use node.js in asp.net mvc application?

I Want to integrate node.js web-terminal emulator into asp.net mvc application. So before that , i would like to know the possibility of integration of node.js with asp.net mvc.

Thanks in advance.

How to implement authentication in multiple "Areas" of asp.net MVC

I have an asp.net mvc application. The application is virtually separated by "Areas". Both Areas have their own Login controllers for authentication. Both Areas have their own Home controllers.

Questions:

How do I implement forms authentication in both areas as there is one web.config for both the areas? The web.config is in the root of the application and not in individual folders of the Area folder.

How do I set the startup "Area"? i.e. Which Area's Home controller should be called first when the project runs?

How to create an input (editorfor) for a field not in the model

I have the following on my EDIT view

@model Inspinia_MVC5.Areas.GlobalAdmin.Models.Empresa

@{
    ViewBag.Title = "Edit";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
    var camposAdicionalesEmpresa = (List<Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad>)ViewData["CamposAdicionalesEmpresa"];
    var valoresCampoAdicionalesEmpresa = (Dictionary<string, string>)ViewData["ValoresCampoAdicionalesEmpresa"];

}

and my controller is like this:

 public ActionResult Edit(int? id)
        {
            var listFields = from b in db.Propiedades
                             where b.Entidad.Nombre == "Empresa"
                             select b;
            ViewData["CamposAdicionalesEmpresa"] = listFields.ToList<Propiedad>();

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Empresa empresa = db.Empresas.Find(id);
            if (empresa.PropiedadesExtra != null)
            {
                XElement xmlTree = XElement.Parse(empresa.PropiedadesExtra);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                foreach (var el in xmlTree.Elements())
                {
                    dict.Add(el.Name.LocalName, el.Value);
                }

                ViewData["ValoresCampoAdicionalesEmpresa"] = dict;
            }

            if (empresa == null)
            {
                return HttpNotFound();
            }
            return View(empresa);
        }

ViewData["ValoresCampoAdicionalesEmpresa"] is a dictionary with key values, and I need to display in an input form that value.

On my razor view I have this

 @if (valoresCampoAdicionalesEmpresa != null)
    {
        <div class="panel panel-default">
            <div class="panel-heading">Propiedades adicionales</div>
            <div class="panel-body">               
                @foreach (Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad propiedad in camposAdicionalesEmpresa)
                {
                    if (propiedad.TipoDeDatos == "Texto")
                    {
                        var valor = valoresCampoAdicionalesEmpresa.Where(p => p.Key == propiedad.Nombre).First().Value;
                        <div class="form-group">
                            @Html.Label(propiedad.Nombre, new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.Editor(valor)
                                @*@Html.ValidationMessageFor(prop => propiedad.)*@
                            </div>
                        </div>
                    }
                }
            </div>
        </div>
    }

If I debug, the valor variable is correctly set, however on the user interface, the textbox is empty.

How can I achieve that?

Get a single text value using linq

I am using this line to return a value, but instead its getting a True

var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First();

This the view data passes from the controller

var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"];

public ActionResult Edit(int? id)
        {
            var listFields = from b in db.Propiedades
                             where b.Entidad.Nombre == "Empresa"
                             select b;
            ViewData["CamposAdicionalesEmpresa"] = listFields.ToList<Propiedad>();

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Empresa empresa = db.Empresas.Find(id);
            if (empresa.PropiedadesExtra != null)
            {
                XElement xmlTree = XElement.Parse(empresa.PropiedadesExtra);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                foreach (var el in xmlTree.Elements())
                {
                    dict.Add(el.Name.LocalName, el.Value);
                }

                ViewData["ValoresCampoAdicionalesEmpresa"] = dict;
            }

            if (empresa == null)
            {
                return HttpNotFound();
            }
            return View(empresa);
        }

check for value null on razor syntax

The following code is failing because propiedadesFormularioDetalle is null. I placed an IF before the block code but still not working, if I remove one of the bracked, then it wont compile

  @if (propiedadesFormularioDetalle != null) { }
                        <div class="panel panel-default">
                            <div class="panel-heading">Propiedades adicionales</div>
                            <div class="panel-body">
                                <dl class="dl-horizontal">
                                    @foreach (KeyValuePair<string, string> propiedad in propiedadesFormularioDetalle)
                                    {

                                        <dt>
                                            @Html.DisplayName(propiedad.Key)
                                        </dt>

                                        <dd>
                                            @Html.DisplayFor(prop => propiedad.Value)
                                        </dd>

                                    }
                                </dl>
                            </div>      
                        }                 
                    </div>

dropdown value not saved in asp.net mvc

I have the following entities:

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

            public virtual Entidad Entidad { get; set; }

            public string Codigo { get; set; }
            public string Nombre { get; set; }
            public string TipoDeDatos { get; set; }
        }

public class Entidad
    {
        [Key]
        public int Id { get; set; }
        public string Nombre { get; set; }

        public virtual ICollection<Propiedad> Propiedades { get; set; }
    }

and in my create view I have this:

<div class="form-group">
        @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.Entidad.Id, (SelectList)(ViewBag.EntidadList), "Seleccionar", new { @class = "form-control" })
        </div>
    </div>

When I debug I can see this on the controller action

 // POST: /GlobalAdmin/Propiedades/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Id,Codigo,Nombre,TipoDeDatos, Entidad")] Propiedad propiedad)
    {
        if (ModelState.IsValid)
        {
            db.Propiedades.Add(propiedad);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(propiedad);
    }

http://ift.tt/1IM8IYw

http://ift.tt/1JVOxsw

Progress Bar using jquery and MVC3

I have a long running process. I created a database table to store status updates and rough completed percentages. The long running process adds status updates to the database as it goes. It's just a basic controller method with lots of stuff in it.

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SaveProjectSiteItems(FormCollection collection)
    {
        //Do long process
    }

I also created a method to check these statuses and update a progress bar.

        [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult GetProgress(int progressBarID)
    {
        this.ControllerContext.HttpContext.Response.AddHeader("cache-control", "no-cache");
        try
        {
            ICOMRepository comRepository = new COMRepository();
            v_ProgressBar vProgressBar = comRepository.GetVProgressBar(progressBarID);

            return Json(new { wasSuccess = true, percent = vProgressBar.Percent, message = vProgressBar.Message });
        }
        catch (Exception ex)
        {
            Log.Error(ex, Request.Path, UserHelper.GetEmail());
            return Json(new { wasSuccessful = false, message = "Error - No progress bar found." });
        }
    }

I use javascript to call this method on a delay.

function progressBarUpdater() {
var data = {
    ProgressBarID: progressBarID
};
setTimeout(function() {
    jsonGetHelper("/site/progress/GetProgress", data, function(results) {
        if (results.wasSuccess) {
            $("#progressBarModal p").text(results.message);
            $("#progressBarModal #progressBar").css("width", results.percent + "%");
            if (results.Percent != 100) progressBarUpdater();
        }
    });
}, 3000);

}

Here is where the long process is started in the javascript.

function saveProjectSiteItems() {

createProgressBar();
$("#projectsiteitemsdialog #ProgressBarID").val(progressBarID);
$('#progressBarModal').modal('show');
jsonFormHelperAsync("#projectsiteitemsdialog", "/site/studies/SaveProjectSiteItems", processSaveProjectSiteItems);
progressBarUpdater();

}

It seems that my controller is still locked doing the long process however. In debugging I can see the javascript call the long process, then move on to call the GetProgress method but it doesn't actually get to the controller method until after the long process is complete, which defeats the purpose.

Can anyone tell me how to modify things so that the GetProcess method actually gets called with the long process is still running? I've found some examples, but they all seem to be using local variables to store the progress data, so I'm not sure how to apply it. Is doing things with a database a bad idea? I was thinking it would have a fringe benefit of logging the long task's various stages.

Load user extract with stored procedure

I have a ASP MVC web application that is required to load a user extract each day from a file. The users in the database should be updated accordingly: deleted if not in source, updated if in source and target, and created if only in source. While doing this, certain rights should also automatically be given to the users. If there is any error, nothing should happen at all.

First I tried to do this with Entity Framework, but the SaveChanges call takes around two minutes to return, which is a lot for the relatively small amount of users (~140 000).

My idea now is to write a stored procedure that would do the updating. I would pass the list of new users as a parameter. The type of my temporary table:

CREATE TYPE [dbo].[TempUserType] AS TABLE 
(
    [Uid] NVARCHAR(80) NOT NULL PRIMARY KEY,
    [GivenName] NVARCHAR(80) NOT NULL,
    [FamilyName] NVARCHAR(80) NOT NULL,
    [Email] NVARCHAR(256) NOT NULL,
    [GiveRight1] BIT NOT NULL,
    [GiveRight2] BIT NOT NULL,
    [GiveRight3] BIT NOT NULL
)

The users:

CREATE TABLE [dbo].[User] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Uid]         NVARCHAR (80)  NOT NULL,
    [GivenName]   NVARCHAR (80)  NOT NULL,
    [FamilyName]  NVARCHAR (80)  NOT NULL,
    [Email]       NVARCHAR (256) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    UNIQUE NONCLUSTERED ([Uid] ASC)
);

The user roles:

CREATE TABLE [dbo].[UserRole] (
    [UserId]      INT NOT NULL,
    [RoleId] INT NOT NULL,
    CONSTRAINT [PK_UserRole] PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
    CONSTRAINT [FK_UserRole_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id]),
    CONSTRAINT [FK_UserRole_Role] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[Role] ([Id])
);

The procedure I am stuck writing:

CREATE PROCEDURE [dbo].[UpdateUsers]
    @extractedUsers TempUserType READONLY
AS

BEGIN TRANSACTION

MERGE
    [dbo].[User] AS trg
USING
    @extractedUsers AS src
ON
    (trg.[Uid] = src.[Uid])
WHEN MATCHED THEN
    UPDATE SET
        trg.GivenName = src.GivenName,
        trg.FamilyName = src.FamilyName,
        trg.Email = src.Email
WHEN NOT MATCHED BY TARGET THEN
    INSERT
        ([Uid], GivenName, FamilyName, Email)
    VALUES
        (src.[Uid], src.GivenName, src.FamilyName, src.Email)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;


COMMIT TRANSACTION

My question: is the use of a procedure with merge appropriate in this case to achieve the performance improvement over EF? How can I attribute roles according to the 3 boolean values that are in the source table?

Roles can be hadcoded, meaning I know that the Right1 corresponds to the RoleId 1, Right 2 to RoleId 2 and Right 3 to RoleId3.

lundi 15 juin 2015

Entity framework forien keys

I am new in MVC and Entity framework, so I have some problem in my first project. So sorry if my question is to noob :(

What I have at this point:
I have table users(ID, Name, Password, TypeID, StatusID) and I have lookup table for this fields TypeID, StatusID UserTypes and UserStatuses.

Here is some code for more clarity

CREATE TABLE [dbo].[Users](
    [ID] [int] NOT NULL,
    [Name] [varchar](512) NOT NULL,
    [Password] [varchar](128) NOT NULL,
    [TypeID] [int] NULL,
    [StatusID] [int] NULL
)

CREATE TABLE [dbo].[UserStatuses](
    [ID] [int] NOT NULL,
    [Description] [nvarchar](128) NULL
)


CREATE TABLE [dbo].[UserTypes](
    [ID] [int] NOT NULL,
    [Description] [nvarchar](128) NULL
)

In UserStatuses Table I store "active", "Blocked" and in UserTypes "Admin", "User", "guest"

Values in UserTypes mey change in future so, I don't wont to convert Users.TypeID field in Enum.(this is important for me !)

What I need:
How display user friendly values "active", "Blocked" for StatusID and "Admin", "User", "guest" for TypeID field, instead of number editor when I am generating view ?

link to some good article is welcome Smile :)

Dynamic Controls in MVC based on database table entries

Hi I have a questionnaire table like :-

Q.no | Question | AnswerControlType

  1. | Name ? | 1
  2. | Gender | 3

Control Type Column entry would be like 1=> Textbox 2=> =Dropdown 3=> Radiobutton etc

Based on these values in the table I need to generate a dynamic View i.e depending on number of table entries we need to create corresponding controls onto a single view.

Please provide me with a template of Model , View and Controller

Further how do i get these control values on Form Post Action Method in the COntroller

dimanche 14 juin 2015

MVC3 POST model binding not working for particular complex model

For some reason, when I post this view model back to the controller and add in the model for binding, it ends up being null. The application that I am working with is a massive one. Also I haven't written much of the code so this model is massive so I will just add the parts that matter, but could other properties be preventing the model binding?

I do know that it has been working but in the last little bit it started not. Maybe it's not even something with the model, would just love some help debugging it.

--- GET Action ---
[HttpGet]
    public ActionResult Categories(int applicationId)
    {
        ...other code.....

        // Get the application
        var application = _sqsApplicationService.Load(applicationId);
        var model = SqsApplicationViewModel.MapFromDto(application);

        // Setup the categories for display and choosing
        var categories = _sqsCategoryService.Load();
        var cats = SqsCategoryViewModel.MapFromDto(categories);
        model.SetupCategoriesForSelection(cats);

        return View(model);
    }

-

--- POST action --
[HttpPost]
    public ActionResult Categories(int applicationId, SqsApplicationViewModel model)
    {
        // Save away the ids they chose
        _sqsApplicationCategoryService.SaveCategories(applicationId, model.Display_Categories.Where(i => i.Selected).Select(i => i.CategoryId).ToList());

        // Complete the step
        _sqsApplicationStepService.CompleteStep(applicationId, SqsStep.Categories);

        return RedirectToAction("Documents");
    }

-

public class SqsApplicationViewModel : IMappable
{
    public int Id { get; set; }
    public int SupplierId { get; set; }
    public int? SqsApprovalLevelId { get; set; }

    .... other properties .....

    public List<SqsChosenCategoryViewModel> Display_Categories { get; set; }

    .... other properties .....
}

-

public class SqsChosenCategoryViewModel
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string CategoryAmountString { get; set; }
    public bool Selected { get; set; }

    public IList<SqsDocumentComplianceViewModel> Documents { get; set; }
}

set font awesome icon into textbox

I have problems set i class into textbox for, my actual view: enter image description here

and I want something like this:

enter image description here

How can I do that? There is my code (razor):

<div class="row">

        <!-- feedback -->
        <article class="feedback">
            <div class="widget-title">Deja un mensaje </div>

             @using (Html.BeginForm("Contact_Partial", "ContactModels", FormMethod.Post))
    {

            <h6>Campos Requeridos*</h6>
            <br />

            @*<div class="input-group">*@

             <div class="col-md-9">
                 @*@Html.LabelFor(model => model.Name, "Nombre*", new { @class = "pull-left" })*@

                 <i class="fa fa-user appointment"></i>  @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @style = "width:100%", @placeholder = "Nombre*" })
                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            </div>

             <br />

             <div class="col-md-9">        
                 <i class="fa fa-envelope appointment"></i> @Html.TextBoxFor(model => model.Email, new { @class = "form-control", @style = "width:100%", @placeholder = "Email*", @type = "email" })

                     @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })


            </div>

             <br />



 <div class="col-md-9">

    <i class=" fa fa-align-left appointment"></i>@Html.TextAreaFor(model => model.Comments, new { @class = "form-control", @style = "width:100%", @placeholder = "Mensaje*" })
     @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
 </div>

HTML CODE:

  <article class="feedback">
            <div class="widget-title">Deja un mensaje </div>

 <form action="/ContactModels/Contact_Partial/1" method="post">                    <h6>Campos Requeridos*</h6>
                 <br />
                 <div class="col-md-9">


                     <i class="fa fa-user appointment"></i>  <input class="form-control" data-val="true" data-val-required="Es necesario que ingrese su nombre" id="Name" name="Name" placeholder="Nombre*" style="width:100%" type="text" value="" />
                         <span class="field-validation-valid text-danger" data-valmsg-for="Name" data-valmsg-replace="true"></span>

                 </div>
                 <br />
                 <div class="col-md-9">        
                     <i class="fa fa-envelope appointment"></i> <input class="form-control" data-val="true" data-val-required="Es necesario que ingrese su correo" id="Email" name="Email" placeholder="Email*" style="width:100%" type="email" value="" />

                         <span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>


                 </div>
                 <br />
     <div class="col-md-9">

         <i class=" fa fa-align-left appointment"></i><textarea class="form-control" cols="20" data-val="true" data-val-minlength="Es necesario que ingrese al menos 10 caracteres" data-val-minlength-min="10" data-val-required="Ingrese algún comentario por favor" id="Comments" name="Comments" placeholder="Mensaje*" rows="2" style="width:100%">

                    <input type="submit" value="Enviar" class="btn button" /> 
                </div>
 </form>
         </article>
     </div>

AND CSS (If I don't use it, it's the same problem, icon appears above the text)

.widget-appointment {
display: none;
 }

 .widget-appointment i,i.appointment{
   position:absolute;
   z-index: 1;
   top: 0;
   left: 0;
   width: 50px;
   height: 50px;
   font-size: 24px;
   line-height: 50px;
   text-align: center;
   color: #fff;
 }
 i.appointment{
   position:relative;
   margin-right:5px;
   margin-bottom:5px;
 }
.widget-appointment i:after,i.appointment:after {
   content: '';
   position: absolute;
   top: 50%;
   left: 100%;
   margin-top: -4px;
   border-top: 4px solid transparent;
   border-bottom: 4px solid transparent;
   border-left-width: 4px;
   border-left-style: solid; 
 }
 .widget-appointment input,
 .widget-appointment textarea {
  height: 50px;
  padding: 13px 10px 13px 65px;
 }

 .widget-appointment .captcha-wrapper input{
   padding: 13px 6px;
 }

 .widget-appointment textarea {
  height: auto;
 }
.widget-appointment .row {
  position: relative;
  margin-bottom: -1px;
 }

I don't know how can I put an into textbox area, I thinks that's the problem So, thanks for reading , any help is very appreciated

How to create a dynamic dropdown in mvc

How to create a dropdown whose option values are coming from controller. controller will be getting it from database table's any column value.

for example if that dropdown is for selecting country, and i have 3 country in my database table's country column, in dropdown it should show the 3 country. And if I add one more value in country table, that also should come in dropdown.

I am new to MVC an this is found bit difficult. I am using mvc5.

How to redirect to view from shared folder

HttpContext.Response.Redirect("~/Shared/views/Error.cshtml", true);

This is not working for me

And how to exclude the certain controllers and actions

samedi 13 juin 2015

Calling actionresult from view

This is my ActionResult()

    public ActionResult pay()
    {
        return View();

    }

    [HttpPost]
    public ActionResult mytry()
    {
        return View();
    }

and this is my view pay.chtml

@using (Html.BeginForm("mytry", "Home"))
{ 
<table>
<tr>
    <td align="center">


        <input type="button" value="submit" />
    </td>
  </tr>

</table>
}

I am not able to call the mytry() action result from here. How to do it?

Getting the property send by api in mvc

I am using paytab's API. (paytab is a payment gate way api). after payement it will return to my actionresult TheReturnPage(). There I need to get the payement_refrence property which the paytab send with the POST method. in asp.net two tier i did it like this and worked for me

 public partial class TheReturnPage : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext c = HttpContext.Current;
        if (c.Request["payment_reference"] != null)
        {

            string paymentReference = c.Request["payment_reference"].ToString();
            if (VerifyPayment(paymentReference))
            {
                //Payment is verified and logging out from payment process
                if (LogoutPayment())
                {
                    TextBox1.Text = "Payment is verified and logged out successfuly";

How can I do the same in MVC? paytab manual you can find here. http://ift.tt/1KNTp3K

vendredi 12 juin 2015

How to create edit view with a dropdownlist

I have the following entities:

 public class Entidad
    {
        [Key]
        public int Id { get; set; }
        public string Nombre { get; set; }

        public virtual ICollection<Propiedad> Propiedades { get; set; }
}




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

        public virtual Entidad Entidad { get; set; }

        public string Codigo { get; set; }
        public string Nombre { get; set; }
        public string TipoDeDatos { get; set; }
    }

and on my edit view

 <div class="form-group">
                            @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.DropDownListFor(m => m.Entidad.Id, (SelectList)(ViewBag.EntidadList), "Seleccionar", new { @class = "form-control" })
                            </div>
                        </div>

However I get this error on the view

The ViewData item that has the key 'Entidad.Id' is of type 'System.Int32' but must be of type 'IEnumerable'. Description

Pathname modified with IE

I have a web site in IIS. When I open it with FireFox I have my path name like this :

http://WebSiteName/ControllerName/ViewName

So in IE 10 I have a string add between web site name and controller name :

WebSiteName/ (F(tXsULdieggBmidgAHhBWIArSZGI2xTHXKFUmtUdW5_3o3hUeInshtdta4A7JUWV13w6_HbIoXQOg3Q3NHJcIX5_TYPCZIg5LecfxTOYMCec1))/ControllerName/ViewName

I don't understand this, any help would be appreciated!

thank you.

jeudi 11 juin 2015

Space between rows in bootrap form not correct

I have the following form, however there is an extra space between 1st and 2nd row.

http://ift.tt/1FbN9vr

However I am not sure how to get rid of it.

This is the html code generated

<div class="form-horizontal">



        <div class="form-group">
            <label class="control-label col-md-2" for="Entidad">Entidad</label>
            <div class="col-md-10">
                <select name="Entidades" class="form-control m-b" id="Entidades"></select>
            </div>
        </div>


        <div class="form-group">
            <label class="control-label col-md-2" for="Codigo">Codigo</label>
            <div class="col-md-10">
                <input name="Codigo" class="text-box single-line" id="Codigo" type="text" value="">
                <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Codigo"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2" for="Nombre">Nombre</label>
            <div class="col-md-10">
                <input name="Nombre" class="text-box single-line" id="Nombre" type="text" value="">
                <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Nombre"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2" for="TipoDeDatos">TipoDeDatos</label>
            <div class="col-md-10">
                <input name="TipoDeDatos" class="text-box single-line" id="TipoDeDatos" type="text" value="">
                <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="TipoDeDatos"></span>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input class="btn btn-primary" type="submit" value="Create">
                <a class="btn btn-white" href="/GlobalAdmin/Propiedades">Cancel</a>
            </div>
        </div>
    </div>

and this is my mvc code view

@model Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad

@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2>Create</h2>
        <ol class="breadcrumb">
            <li>
                @Html.ActionLink("List", "Index")
            </li>
            <li class="active">
                <strong>Create</strong>
            </li>
        </ol>
    </div>
    <div class="col-sm-8">
        <div class="title-action">
            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-primary"})
        </div>
    </div>
</div>


<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Create Propiedad</h5>
                </div>
                <div class="ibox-content">

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

    <div class="form-horizontal">
        @Html.ValidationSummary(true)


        <div class="form-group">
            @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Entidades", (IEnumerable<SelectListItem>)ViewData["Entidades"], new { @class = "form-control m-b" })
            </div>
        </div>


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

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-white"})
            </div>
        </div>
    </div>
}

                </div>
            </div>
        </div>
    </div>
 </div>

Create view for a child-master relationship

I have an entity called Entity, (lol).

        public class Entidad
    {
        [Key]
        public int Id { get; set; }
        public string Nombre { get; set; }

        public virtual ICollection<Propiedad> Propiedades { get; set; }
}

I also have an entity called Properties

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

        public virtual Entidad Entidad { get; set; }

        public string Codigo { get; set; }
        public string Nombre { get; set; }
        public string TipoDeDatos { get; set; }
    }

My Create view with the automated scaffolding gets rendered like this http://ift.tt/1S8gHn6

However, I should be able to select the Entity from a dropdown list.

this is the automatically generated view

@model Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad

@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2>Create</h2>
        <ol class="breadcrumb">
            <li>
                @Html.ActionLink("List", "Index")
            </li>
            <li class="active">
                <strong>Create</strong>
            </li>
        </ol>
    </div>
    <div class="col-sm-8">
        <div class="title-action">
            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-primary"})
        </div>
    </div>
</div>


<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Create Propiedad</h5>
                </div>
                <div class="ibox-content">

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

    <div class="form-horizontal">
        @Html.ValidationSummary(true)

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

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-white"})
            </div>
        </div>
    </div>
}

                </div>
            </div>
        </div>
    </div>
 </div>

Questions is how can I add the dropdown and make it fill the values from the entities?

The controller for path '/GlobalAdmin/GlobalAdmin/IndexGlobalAdmin' was not found or does not implement IController

I have the following structure:

One area called global admin, the area has a global admin controller, and its view

http://ift.tt/1QrCvfO

My code is as follows:

GlobalAdminController:

namespace Inspinia_MVC5.Areas.GlobalAdmin.Controllers
{
    [AuthorizeUser(Roles = "admin")]
    public class GlobalAdminController : Controller
    {
        // GET: GlobalAdmin

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

and on my home controller I have the following:

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (User.IsInRole("admin"))
            {
                return RedirectToAction("IndexGlobalAdmin", "GlobalAdmin", new { area = "GlobalAdmin" });
            }
            if (User.IsInRole("Company Admin"))
            {
                return RedirectToAction("Index", "CompanyAdmin", new { area = "CompanyAdmin" });
            }
            return View();
        }

the index view is easy

@{
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
    ViewBag.Title = "Index";
}

<h2>Index</h2>

However I get this error:

The controller for path '/GlobalAdmin/GlobalAdmin/IndexGlobalAdmin' was not found or does not implement IController

What is my problem?

What is the best practice for maintain a menu after a page reload? I have this custom code which feels wrong

I have a custom Menu which loads a new MVC View for each click as I want. I load the new View by setting window.location.href. To make it work I have to set the baseURL (the name of the website) each time. To Store the state of the menu I use URL's querystring.

My concerns is in the use of:

  1. '/WebConsole53/' // hardcode baseurl i have to apply each time manually
  2. Setting window.location.href to load the new View from JavaScript // Is this the best way or should I use some URL/Html helpers instead?
  3. I store the state of the selected menuItem in the querystring ("menu") // Is it more common to store that kind in Session/Cookie?

Any thoughts, corrections and suggestions would be much appriciated - thanks.

_Layout.cshtml

var controller = $self.data('webconsole-controller');
var action = $self.data('webconsole-action');
var menu = "?menu=" + $self.attr('id');
var relUrl = controller + "/" + action + menu;
var url = urlHelper.getUrl(relUrl);
window.location.href = url;

UrlHelper.js

var urlHelper = function () {
    var getBaseUrl = '/WebConsole53/',

        buildUrl = function(relUrl) {
            return getBaseUrl + relUrl;
        };

    var getUrl = function(relUrl) { // relUrl format: 'controller/action'
        return buildUrl(relUrl);
    };

    return {
        getUrl: getUrl
    };
}();

I Use MVC 5.

mercredi 10 juin 2015

JSON object passed to Controller is NULL

I understand this question has been posted a thousand times, but I have tried every solution to no avail.

I have this JSON object:

{ 
  "manufacture":"HP",
  "model":"testModel",
  "serialNumber":"testSerial",
  "description":"Test Description",
  "checkIn":true,
  "stand":false,
  "tilt":true,
  "pivot":false,
  "heightAdjust":true,
  "size":27,
  "portTypes":"2 VGA",
  "resolution":"1080P"
}

I pass this JSON object to the controller which is just

Function submitMonitor(monitor As Monitor)
  Return False
End Function

The ajax call to pass to the controller is as follows:

jQuery.ajaxSettings.traditional = true;
$.ajax({
    url: '@Url.Action("submitMonitor", "Home")',
    type: 'GET',
    contentType: 'application/json',
    //contentType: "application/json; charset=utf-8",
    //dataType: 'json',
    //processData: true,
    data: JSON.stringify(data)
});

I have tried passing:

data:data

I have tried without the ajaxSettings.traditional line. I have tried with the commented blocks on or off, but still no luck.

Here is the class that it should be passing to.

Public Class Monitor : Inherits HardwareData
   Public stand As Boolean
   Public tilt As Boolean
   Public pivot As Boolean
   Public heightAdjust As Boolean
   Public size As Integer
   Public portTypes As String
   Public resolution As String
End Class

Here is the class that Monitor inherits:

Public Class HardwareData
   Public key As Integer
   Public manufacture As String
   Public model As String
   Public serialNumber As String
   Public createdBy As String
   Public createdTimeStamp As Date
   Public description As String
   Public checkIn As Boolean
End Class

Whenever the controller gets called though, looking at the monitor variable in debugger, I see that all the values are set to Nothing.

Any idea what could be causing this?

Skip login on MVC 3 application (SSO)

I have an MVC application which is using forms authentication. In the global.asax file, whenever trying to get into a site, you'll be redirected to login form:

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

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

I also have another application which should call this application in an iframe. The iframe should have a link of one of my inner pages and shouldn't go through the login page (the other application sends the username, and then I have an authentication method), and get directly to the inner page, but I can't seem to get the url of the inner page.

I tried using System.Web.HttpContext.Current.Request.UrlReferrer but it appears null

How can I get this info and skip the login page?

Thanks

mardi 9 juin 2015

Image Gallery control not loading

I am currently working on a project that has decided to incorporate Image Gallery from DevExpress MVC. Previously when put into the page, we had an bug come up where if the SettingsFullscreenViewer.Visible was set true, you could not upload. However, once turned to false, we could upload and do whatever on development.

We pushed to our testing site and discovered now we get the following error: "Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper.'" It only fires when there is an image within the Image Gallery for that particular item.

I am somewhat at a loss and was curious if anyone else has had issues with this control also.

ObjectContext is disposed, can not longer used

Example Code:

private static list;
public void SetList ()
{
var query = Container.Advices.Where ();
list= query.ToList();
}

public void doStuff ()
{
var temp= list.where (...).ToList ();
}

problem situation:

When i call the first time SetList, all worked fine. Now, a second is SetList called. I can see in the method, there are all objects, but in the second method doStuff is an exception thrown: ObjectContext is disposed ... I'm not understanding why. I saw the data is loaded correctly in the list and not a second later i can ' t load the navigation properties.

How can i fix this?

RedirectToAction doesn't happen when I start with an AJAX call

RedirectToAction "doesn't work" when is use an ajax call, why is that?

The Login action sends me to the action Index with RedirectToAction, so I can see that view is returned. And the AJAX call end up in done. Why doesn't the URL change to ../home/index as I would expect?

If I in done manually call window.location.href = "/WebConsole53"; I will get the redirect I want, but I would rather use the redirect on the server. Can someone figure out what is the problem? Thanks.

Ajax call:

$('#btnLogin').on('click', function() {
    var url = urlHelper.getUrl('Account/login');
    var data = {
        username: $('#inputLoginUsername').val(),
        password: $('#inputLoginPassword').val()
    }

    $.ajax({
        url: url,
        method: "POST",
        data: data
    })
    .done(function (html) {
        console.log('done login');
        //window.location.href = "/mySite"; // this works
    })
    .fail(function (jqXhr, textStatus, errorThrown) {
        console.log('failed');
    });
});

Action:

[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public ActionResult Login(string username, string password/*, LoginViewModel model*/, string returnUrl)
{
    //if (!ModelState.IsValid)
    //{
    //    return View(model);
    //}

    // This doesn't count login failures towards account lockout To enable password failures to trigger account lockout, change to shouldLockout: true
    //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    //switch (result)
    //{
    //    case SignInStatus.Success:
    //        return RedirectToLocal(returnUrl);
    //    case SignInStatus.LockedOut:
    //        return View("Lockout");
    //    case SignInStatus.RequiresVerification:
    //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    //    case SignInStatus.Failure:
    //    default:
    //        ModelState.AddModelError("", "Invalid login attempt.");
    //        return View(model);
    //}

    return RedirectToAction("Index", "Home");
    //return RedirectToActionPermanent("Index", "Home");
    //return RedirectToLocal(returnUrl);
    //return RedirectToAction("ShowDashboard", "Dashboard");
}

Home Index:

public ActionResult Index()
{
    return View();
//            return RedirectToAction("Login", "Account");
//            return RedirectToAction("ShowDashboard", "Dashboard");
}