samedi 30 avril 2016

Is there any way to do Partial page refresh on page load without writing JQuery in Laravel?

I know both .NET and PHP and as per my understanding EntityFramework in .NET is same thing as Laravel in PHP.

in .NET we have @using (Ajax.BeginForm that renders forms same as {!! Form::open in PHP.

@using (Ajax.BeginForm does not refresh the whole page on form submit and I don't need to write JQuery to do this. So, basically it acts same as JQuery.ajax

Question: Is there any way to do Partial page refresh on form submit without writing JQuery in Laravel?

vendredi 29 avril 2016

Show data from multiple Postgres V9.4 servers in one web page

We are using postgres v9.4 in our project. We are using MVC Kendo UI and .Net Framework on the Front End. We have 4 database servers for Postgres and each at different physical machine.

GOAL : What I want to do is to prepare some sort of mechanism which will fetch data from all the servers and will accumulate and show in our web page as a single dataset. Currently I am doing this by providing a dropdown box for database selection.

Possible Solutions to achieve the goal :

  1. Create one postgres function in any of the postgres server, and from there we can use db_link to get data from other 3 postgres servers and Return the combined result set of data. But there are few many issues/blots in using this approach. Since we are using custom paging it may become difficult to bifurcate the data. say my page size is 50 then to bring exact 50 results of dataset I many need to divide 50 among 4 postgres servers.
  2. Since we are using .Net Framework what I can do is to make 4 Async calls from application and then merge the result set in One and display.

My question is can I use any other approach, or how can I modify/optimize current approaches.

Create a click event in MVC3 View

I am not sure if this is even possible buts its driving me insane looking for a solution. I have an MVC3 web application. I can not use the controller to run code OnClick so ActionResult is not an option. Is there any other way to run a method OnClick in MVC3 that does not involve invoking the method from the controller. For a example button in the view that executes a method which is also in the view (I know this is a terrible thing to do but its all I can do at the moment) I can put the method in the view and it executes on load but I need to execute OnClick. Any help on this matter would be greatly appreciated.

jeudi 28 avril 2016

Mail not sending in mvc 3

i have posted my source that having porblem named

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 68.178.232.62:25

i have implemented by ref of

http://ift.tt/1pNovkD

please help me to solve this issue

thanks in advance :)

View Page

 @using (Html.BeginForm("Emailto", "Home", FormMethod.Post))
    {
@Html.TextBoxFor(a => a.Position, new { @readonly = "readonly", @id = "Position", @name = "Position" })
  <input type="text" value="" id="txtname" name="txtname" required />
  <input type="email" value="" id="txtemail" name="fromEmail"  required />
<input type="submit" id="btnApply" name="btnApply" value="Apply" />

Controller

[HttpPost, ValidateInput(false)]
        public ActionResult Emailto(string Position, string txtname, string fromEmail)

        {
            EmailManager.SendMessage(Position, txtname, fromEmail);
            return Redirect("Index");
        }

EmailManager

[System.Web.Services.WebMethod]
        public static void SendMessage(string Position, string txtname, string fromEmail)
        {
            const string SERVER = "relay-hosting.secureserver.net";
            const string TOEMAIL = "riayz@acute.company";
            MailAddress from = new MailAddress(fromEmail);
            MailAddress to = new MailAddress(TOEMAIL);
            MailMessage message = new MailMessage(from, to);

            message.Subject = "Position " + Position;
            message.Body = "Message from: " + Position + " at " +
                           fromEmail + "\n\n" + txtname;
            message.IsBodyHtml = false;
            SmtpClient client = new SmtpClient(SERVER);
            client.Send(message);
        }
    }

How to Convert a base64 image url to User Friendly URL in ASP.NET

I'm retrieving image from database which as stored in base64 format. Here my requirement is, I want to convert a base64 image url into user friendly url. I tried many solutions, but I didn't get as i expected. Can anyone suggest me how to achieve this.

For Example :-

this is bas64

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkAAAAJACAYAAABlmtk2AAAgAElEQVR4Xu 3dQYoj5paEUdng7Zhemie1ipz00rwfg2nSUOPKvEdCdPD11IqreucPQZCT/u3j4+PPPx6P3x//D//vn8 fj389/dv/+9zxe/u9x//mt+ecvAvVH9DybvxvKhU//3/734+N//vrx42859K7s57/987v797/nBfJ/j/ vPb80/fxGoP6Ln2fzdUC58+jeARBCz/QAQEOP5IyDG80dAjOePgBjPHwEx3gBCQI33A1BBy+dvfprOXw Utn7/5aTp/FbR8A8j8ON0PgAnpQP7Ex+H8mZAO5E98HM6fCelAA4j4PNwPwA3lQv6i59n83VAu5C96ns 3fDeVCA0j0npDtB/AERDiRP+A9IZr/ExDhRP6A94Ro/k9AhBMNIMB7RrQfwDMU7zfyv9s9I5n/MxTvN/ K/2z0jmf8zFO83GkB3u6ck+wE8hfF8JP8z3VOC+T+F8Xwk/zPdU4L5P4XxfKQBdKZ7TrAfwHMcr1fyv8 o9J5f/cxyvV/K/yj0nl/9zHK9XGkBXuSfl+gE8CfJ4Jv8j3JNi+T8J8ngm/yPck2L5PwnyeKYBdIR7Vq 6/oieZ/N3Q7mQv+h5dsG/AeQ9OF9YKFAD6Pz8HKw/TEgH8ic+DufPhHRgwb8BRBWw8EKBGkDWAUnXH9H zbP5uKBfyFz3PLvg3gLwH5wsLBWoAnZ+fg/WHCelA/sTH4fyZkA4s+P/28fHx5x+Px+8k8abwP4/Hv59 f3b//PQ+Q/3vcf35r/vmLQP0RPc/m74Zy4dP//wBHqel8UTBFDwAAAABJRU5ErkJggg==" />

i want to get instead of base64

<img src="http://ift.tt/24obXjb />

how to achieve this any suggestion

Error trying to create outlook taskitem in web server app (asp.net mvc5)

  • Using VS 2013 on MVC 5 project.

I' trying to send a task to outlook from an email. I've read several posts about and so far I was able to compile the following code, but it fails when trying to create the TaskItem.

        public void SendTask()
    {
        // This creates OK
        var OutlookApp = new Microsoft.Office.Interop.Outlook.Application();

        // RUN TIME error error here
        Outlook.TaskItem task = OutlookApp.Session.Application.CreateItem(Outlook.OlItemType.olTaskItem) as Outlook.TaskItem;

        task.Subject = "Tax Preparation";
        task.StartDate = DateTime.Parse("4/29/2016 8:00 AM");
        task.DueDate = DateTime.Parse("4/30/2016 8:00 AM");
        task.Assign();
        task.Recipients.Add("support@example.com");
        task.Recipients.ResolveAll();
        task.Send();
    }

Is this possible to send email in mvc 3 without password

i have a form check from that will send mail with data using following code

Controller

[HttpPost, ValidateInput(false)]
        public ActionResult Emailto(string Position, string txtname, string txtemail, string txtmsg)

        {
            EmailManager.Enquiry(Position, txtname, txtemail, txtmsg);
            return Redirect("Index");
        }

EmailManager:

public static void Enquiry(string Position, string txtname, string txtemail, string txtmsg)
        {
            using (var client = new SmtpClient())
            {
                using (var message = new MailMessage(txtemail, EmailTo))
                {
                    message.Subject = "Job Entry";
                    message.Body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Position: " + Position +
                        ", </p> <p>Email<span>:</span>" + txtemail +
                         ", </p> <p>Name:" + txtname +
                    ", </p> <p>Message:" + txtmsg +
                    ",</p>"
                        + "</a></p><div></div><div></div></body></html>";

                    message.IsBodyHtml = true;
                    client.EnableSsl = true;
                    client.Send(message);
                };
            };
        }

In web config

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="smtp.gmail.com" port="587" userName="ex@gmail.com" password="pwd" />
      </smtp>
    </mailSettings>
  </system.net>

My question ,

1.is this possible to send a mail without network host
2. you can see a textbox(email) in enter image description here, is this possible to send a mail from textbox(email id ) to xyz@gmail.com ??

thanks in advance

mercredi 27 avril 2016

How to filter rows in the jqueryGrid based on certain fields?

I have a dropdown menu item on the navigation bar of the jqgrid. Each menu item shows the count of the rows fulfilling certain condition. For example, number of rows that have 'XYZ' property set to true. My problem here is, When i click on this menu item, i would like to show just those rows in the grid. I tried Oleg's solution and looked online, but doesn't help. I tried this too-

var f = { groupOp: "OR", rules: [] };
f.rules.push({ field: 'XYZ', op: 'eq', data: true });
$grid[0].p.search = true;
$.extend($grid[0].p.postData, { filters: JSON.stringify(f) });
    $grid.trigger('reloadGrid');

I get an error as'stype' is undefined or null reference. basic info of how the grid is setup:

setupGrid: function(grid, pager){
$(mygrid).jqGrid({datatype: 'local', 
                 mtype: 'GET',     
                 url:  "myurl",                       
                 colNames: colNames,
                 colModel: colModel,
                 altRows: false,
                 pager: $(pager),
                 loadonce: true,
                 sortable: true,
                 multiselect: true,
                 viewrecords: true,
                 beforeProcessing: function (data) {
                     setSearchSelect(data, 'ABC');
}
 }).navGrid(pager, { add: false, edit: false, del: false, search:false }).trigger('reloadGrid', [{ current: true }]);

Please help !

How to load main Renderbody as partial view

I am using Asp.net mvc 4 application. I have Accordian control in my master page with 5 Click events ( each Click event will route to different controllers). Ex : Home Click will be Home/Index page.

How to load this controllers partially when I click on Accordian control on each link?

Thanks in advance.

Why does input CSS change after unobtrusive validation in mvc3

I have an old MVC3 project, and noticed one of the text field's CSS was changing after input. Text fields appear to lose their CSS or class after being validated.

Here's the code I've been using to narrow down the issue:

Layout

<!DOCTYPE html />
<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title>@ViewBag.Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=8"/>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
    @RenderBody()
    <script src='@Url.Content("~/Scripts/jquery.validate.min.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")' type="text/javascript"></script>
</body>
</html>

View

<h2>DummyView</h2>

<p>No Class</p>
<input type="text" />

<p>With Class But Outside Form</p>
<input type="text" class="big-text-field" />

@using (Html.BeginForm())
{
    <p>With Class Inside Form</p>
    <input type="text" class="big-text-field" />
}

CSS

input[type="text"][class="big-text-field"]
{
    width: 400px;
}

.field-validation-valid
{
    display: none;
    font-family: Arial;
}

The field with the big-text-field class added outside the form stays 400px after input and losing focus. The field inside the form starts out with 400px, but returns to the size of the classless field outside the form after input and losing focus. If I remove the validation scripts from layout, or the .field-validation-valid CSS, it no longer changes.

Why would this be, and is there a way to prevent it?

Thank you in advance for any advice.

How we find Postal code / zip code by giving City Name in asp.net MVC (c#)?

I enter City Name of UK like Derby/Swindon. I want to get postal code of these cities? Like this more cities.

Call Partial Aspx inside razor MVC3 page

i want to call partial ReportViewer.aspx from a page in MVC3 project but the partial cant find the location and show an error like this how can i resolve it?

Error location didn't show .aspx location in all path

the global asax route of my project :

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Account", action = "Login", id = UrlParameter.Optional },
    new[] { "ISpace.Controllers" }
);`

o365 multi tenant issue in mvc

I have taken the sample code from the GIT for multi-tenant. http://ift.tt/1Aa4RhQ

In http://ift.tt/PGgCqW i enabled MULTI-TENANT to YES. But when ever i tried to login i am getting error as clientcredential is null. I tried with below code .

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using O365_WebApp_MultiTenant.Models;
using O365_WebApp_MultiTenant.Utils;
using Owin;
using System;
using System.IdentityModel.Claims;
using System.Threading.Tasks;
using System.Web;

namespace O365_WebApp_MultiTenant
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = SettingsHelper.ClientId,
                    Authority = SettingsHelper.Authority,

                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // instead of using the default validation (validating against a single issuer value, as we do in line of business apps (single tenant apps)), 
                        // we turn off validation
                        //
                        // NOTE:
                        // * In a multitenant scenario you can never validate against a fixed issuer string, as every tenant will send a different one.
                        // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation.
                        // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee, 
                        //       you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you, 
                        //       and block access if that’s not the case.
                        // * Refer to the following sample for a custom validation logic: http://ift.tt/1v1GtBi

                        ValidateIssuer = false
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. 
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://ift.tt/1lrdChK").Value;
                            string signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantID), new ADALTokenCache(signInUserId));

                            // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context
                            // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, SettingsHelper.AADGraphResourceId);

                            return Task.FromResult(0);
                        },

                        RedirectToIdentityProvider = (context) =>
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = (context) =>
                        {
                            // Suppress the exception if you don't want to see the error
                            context.HandleResponse();
                            return Task.FromResult(0);
                        }
                    }

                });
        }
    }
}

mardi 26 avril 2016

working with validations on dropdownlist in kendolistview

I am having a editTemplate for kendolistview which is working fine. I have a dropdown in that template as below

<li>
                <label>
                    <strong>Country :</strong>
                    <input name="CountryId" class="InputRequired" id="CountryId" data-source="countryDataSource" data-role="dropdownlist" data-text-field="Name" data-value-field="CountryId" data-filter="contains" required="required" validationmessage="Country is required." />
                    <span data-for="CountryId" class="k-invalid-msg"></span>
                </label>
            </li>

Even after writing required="required", validation does not firing as it is mentioned in below url that input validation works . http://ift.tt/1T1VHfM

Please help asap

here is my datasource

  var countryData = [];

 var countryDataSource = new kendo.data.DataSource({
        data: countryData
    });

I am Getting this ERROR "ErrorGeneratingOutput"

Hello can anyone please help me to solve this error.

I am Getting this ERROR "ErrorGeneratingOutput" .context.cs and model.cs files every time i create model using Database First Approach

In Context.cs the error is: A namespace cannot directly contain members such as fields or methods c:\users\naseer\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\Models\Model1.Context.cs 1 1 WebApplication3

In Model.cs the error is:

Error 4 A namespace cannot directly contain members such as fields or methods c:\users\naseer\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\Models\Model1.cs 1 1 WebApplication3

lundi 25 avril 2016

Limit amount of text shown in data column in telerik grid mvc3

Am using telerik grid in MVC3 , my problem is how can i show limited text in a column that bound from database.

That means

i have a column with 1000 nvarchar data in database but i need to display only 250 in a column in a grid

ASP.NET MVC3 example with PostgreSQL

everybody! I want to port VS2010 ASP.NET MVC3 example to Mono, but working with PostgreSQL. I ported it, but by default it works with SQLite DB (ASPNETDB in App_Data). I tried to change "connectionstrings" section in Web.config file, but nothing changed (last Mono version in Debian 8.3 repo).

How is it possible to change it?

Thank you in advance.

How to use where clause in LINQ to display specific row?

I need to display only the specific row from the xml ,specific to the email id of the employee.

By this piece of code i'm returning the list of all the employees.

List employees = new List();

            employees = (from rows in ds.Tables[0].AsEnumerable()

                         select new Employee
                         {
                             EmployeeID = rows[0].ToString(),
                             Name = rows[1].ToString(),
                             Email = rows[2].ToString(),
                             DateOfBirth = rows[3].ToString(),
                             Country = rows[4].ToString(),
                             ContactNo = rows[5].ToString(),
                             EmployeeType = rows[6].ToString(),
                             Password = rows[7].ToString(),
                             ConfirmPassword = rows[8].ToString(),
                         }).ToList();
            return employees;

how do i put a where condition that should check the xml email node and display the respective row. Please HELP!

how to add ref to bundle from mvc controller using https in ref

when i add https links as an ref in bundle it is not working, this is my controller code

  public async Task<JsonNetResult> GetCustomePageById(string customepagetemplateid)
    {
        TemplateEacpViewModel model = null;
        resource = "/api/custompagetemplates/" + customepagetemplateid;
        var data = await Get<CustomPageTemplateDetailModel>();
        model = JsonConvert.DeserializeObject<TemplateEacpViewModel>(data.Data.JsonData);
           BundleCollection bundles= new BundleCollection ();
           bundles.Add(new ScriptBundle("~/bundles/scripts/customPages").Include("http://ift.tt/1pxAFy2"));

        return new JsonNetResult { Data = model };
    }

Get checkbox value placed in partial view table

I am very much new to MVC convept. I have two model class with 1 to many relation. find below the code.

Role:

public partial class AppRole
{
    public AppRole()
    {
        AppPermissions = new HashSet<AppPermission>();
        AppUsers = new HashSet<AppUser>();
    }

    public int AppRoleId { get; set; }

    [Required]
    public string RoleName { get; set; }
    public string RoleDescription { get; set; }
    public bool IsSysAdmin { get; set; }
    public virtual ICollection<AppPermission> AppPermissions 
    { get; set;  }
    public virtual ICollection<AppUser> AppUsers { get; set; } 
}

Permission:

public partial class AppPermission
{
    public AppPermission()
    {
    }

    public int AppPermissionId { get; set; }

    [Required]
    public string Name { get; set; }

    public bool Enable { get; set; }

    [Required]
    [StringLength(50)]
    public string PermissionDescription { get; set; }

    public Guid AppRoleId { get; set; } 
    public AppRole AppRole { get; set; }
}

AppPermission is used to set the access permission to different modules. For Eg: 1. User 2. Role 3. Products 4. Customer

Permission is created for every module using checkbox Enable rendered in the table.

When RoleCreate view is rendered, i want permission to be part of the view as a table and the rows are added during runtime which is saved to database when role is saved.

I am able to get the RoleCreate working and get the permisions using partial view. However, i am not able to get the permissions table checkbox data when role is saved.

Find below RoleCreate and ParmissionPartialView code.

RoleCreate:

@model WebOPMS.Models.AppRole
@{
    ViewBag.Title = "Create Role";
}
<script type="text/javascript">
    $(document).ready(function () {
        $(":input[type='submit']").button();
        $(":input[type='button']").button();
     })
</script>
<div class="panel">
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <div class="form-horizontal">
        <h3>
            Create Role
        </h3>

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(m => m.RoleName, new { @class = "col-md-2  control-label" })
            <div class="col-md-3">
                @Html.TextBoxFor(m => m.RoleName, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.RoleName, "", new {   @class = "text-danger" })
            </div>

            @Html.LabelFor(m => m.IsSysAdmin, new { @class = "col-md-2 control-label" })
            <div class="col-md-1">
                @Html.CheckBoxFor(m => m.IsSysAdmin, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.IsSysAdmin, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.RoleDescription, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextAreaFor(m => m.RoleDescription, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.RoleDescription,   "",                     new { @class = "text-danger" })
            </div>
        </div>

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

    <h4>
        List of Permissions
    </h4>
    @*@Html.Partial("PermissionPartialView", Model)*@
    @Html.Partial("PermissionPartialView", Model.AppPermissions)

}
</div>


<div>
    @Html.ActionLink("Go to Roles", "RoleIndex", "Admin")
</div> 

PermissionPartialView:

    @model IEnumerable<WebOPMS.Models.AppPermission>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
    <th>
        Name
    </th>
    <th>
        Enable
    </th>
    <th>
        PermissionDescription
    </th>
    <th>
        @Html.DisplayNameFor(model => model.AppRoleId)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.CheckBoxFor(modelItem => item.Enable)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PermissionDescription)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.AppRoleId)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.AppPermissionId     }) |
        @Html.ActionLink("Details", "Details", new { id=item.AppPermissionId }) |
        @Html.ActionLink("Delete", "Delete", new {     id=item.AppPermissionId })
    </td>
</tr>
}

</table>

Find below code of RoleCreate Action in the controller:

public ActionResult RoleCreate()
    {
        AppRole _approle = new AppRole(); 
        AppUser user = database.AppUsers.Where(r => r.Username ==  User.Identity.Name).FirstOrDefault();
        ViewBag.List_boolNullYesNo = this.List_boolNullYesNo();

        Assembly asm =  Assembly.GetAssembly(typeof(WebOPMS.MvcApplication));

        var controlleractionlist = asm.GetTypes()
                .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
                .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
                .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
                .Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
                .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();

        List<AppPermission> perList = new List<AppPermission>();

        var list = new List<RolePermissionEditorViewModel>();

        foreach (var st in controlleractionlist)
        {
            if ((perList.Any(item => item.Name == string.Format("{0}-{1}",
                GetSplitString(st.Controller, "Controller"), st.Action))) == false)
            {
                AppPermission per = new AppPermission();
                RolePermissionEditorViewModel newMdl = new RolePermissionEditorViewModel();
                newMdl.Name = string.Format("{0}-{1}", GetSplitString(st.Controller, "Controller"), st.Action);
                newMdl.IsEnable = true;
                list.Add(newMdl);

                per.Name = string.Format("{0}-{1}", GetSplitString(st.Controller, "Controller"), st.Action);
                per.Enable = true;
                _approle.AppPermissions.Add(per);
                perList.Add(per);
            }
        }

        var outObj = list.Select(row => new SelectListItem()
        {
            Text = row.Name,
            Value = row.PermissionId.ToString(),
            Selected = row.IsEnable
        });

        ViewBag.keydata = outObj;

        ViewData["pers"] = perList;
        return View(_approle);
    }

I want permission table to be populate in runtime with chebox and when submit is pressed both role create and permission screen to be saved to database.

Please help me with this so that i can progress in this personal project.

Regards,

Shri

dimanche 24 avril 2016

Default code generation is disabled for model

Hello can anyone please help me to solve this problem.

Default code generation is disabled for model 'C:\Users\abidmajeed\Desktop\Documents\Visual Studio 2012\Projects\WebApp\WebApp\Models\Mymodel.edmx'. // To enable default code generation, change the value of the 'Code Generation Strategy' designer // property to an alternate value. This property is available in the Properties Window when the model is // open in the designer.

Want to use same model twice on same view with different type?

Currently I am working with asp mvc view I want to render data on one view...that have display data and create form on same view but it can not be done..because controller return IEnumerable type data and create form's editorfor does not contain definition for that.

I have one model "T4.Models.Order"

if i use this model as @model IEnumerable<T4.Models.Order>

create form razor syntax shows error

if i use this model as @model T4.Models.Order

display data show's error

Here is my code

@model IEnumerable<T4.Models.Order>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table table-striped table-bordered" cellspacing="0" width="100%">
     <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.CustomerID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CustomerID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.OrderDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.RequiredDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShippedDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipVia)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Freight)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipAddress)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipCity)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipRegion)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipPostalCode)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ShipCountry)
            </th>

        </tr>
    </thead>
        @*@{
            IEnumerable<T4.Models.Order> m = @model;
        }*@
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.OrderDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.RequiredDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShippedDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipVia)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Freight)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipAddress)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipCity)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipRegion)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipPostalCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ShipCountry)
            </td>
        </tr>
    }

    </table>
</body>
</html>



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Note : I don't want to change anything on controller side.

Pivot Grid in asp.net mvc

Any one used pivot grid in asp.net mvc ? if yes then help me I want to adjust grid like attendance sheet like excel sheet which have list of students and have columns of days of that month, I don't know how to write its model and all other code related to that

samedi 23 avril 2016

Need a alternate approch to do SQL to LINQ conversion

I'm trying to get a particular result set for my View to bind. I'm new to Linq expression, so I'm not very sure about the different ways of doing it.

Here is my MenuModel

public class MenuModel : DisposeBase
    {
        public string ParentID { get; set; }
        public string ParentName { get; set; }
        public List<MenuItemModel> MenuItems { get; set; }
    }

My MenuItemModel

public class MenuItemModel : DisposeBase
    {
        public string ChildID { get; set; }
        public string ChildName { get; set; }
        public string PageURL { get; set; }
    }

MenuModel is the output type I'm expecting as a result set. I'm getting result set of type DataTable from backend

DataTable dtable = oDatabase.ExecuteAdapter(System.Data.CommandType.StoredProcedure, "SP_GETUSERNAVMENUDATA");

Here is my SQL result set,

My DataTable will looks like this

Now I need to convert this Datatable to type MenuModel.

I tried to Query distinct MenuModel and based on that I'm building MenuItemModel object.

List<MenuModel> lstMenuModel = dtable.DataTableToList<MenuModel>()
                                            .GroupBy(p => new { p.ParentID, p.ParentName })
                                            .Select(g => g.First())
                                            .ToList<MenuModel>();

            foreach (MenuModel parentItem in lstMenuModel)
            {
                List<MenuItemModel> lstUserMenuItemData = dtable.DataTableToList<MenuItemModel>()
                                                .Select(i => new { i.ChildID, i.ChildName, i.PageURL, i.ParentID })
                                                .Where(i => i.ParentID.Equals(parentItem.ParentID))
                                                .ToList<MenuItemModel>();
            }

But still I'm getting conversion error while building MenuItemModel. Now I wanted to know, is there any best practice to do this same conversion of these nested class type? I'm sure there should be something simple to do so.

Any help could be appreciated. Thanks!

Note: DataTableToList is a method that will convert DataTable object to specific generic type

vendredi 22 avril 2016

Sequential await VS Continuation await

I was wondering what is the best/correct way of writing asynchronous code that is composed of two (or more) async and dependent (the first have to finish to execute second) operations.

Example with async/await:

await RunFirstOperationAsync();
await RunSecondOperationAsync();

Example with Continuation:

await RunFirstOperationAsync()
    .ContinueWith(t => RunSecondOperationAsync());

Dijit Selects using Store in asp.net mvc3

I want to use Selectlist Dijit load data from SQL, i use Dojo + Asp.net MVC3, my code looks like the follow, but i don't know why my code isn't working. On view:

    <div id="stateSelect"></div> 
    <script>
        dojo.require("dijit.form.Select");
        dojo.require("dojo.data.ItemFileReadStore");
        dojo.ready(function () {
            // create store instance referencing data from states.json
            var stateStore = new dojo.data.ItemFileReadStore({
                url: "/Home/GetHuyenTP"
            });               
            // create Select widget, populating its options from the store
            var select = new dijit.form.Select({
                name: "stateSelect",
                store: stateStore,
                maxHeight: -1 
            }, "stateSelect");
            select.startup();

        });
    </script>

On HOmecontroller

    public JsonResult GetHuyenTP()
    {
        hmodel.GetListHuyenTp(); //it is List<SelectListItem>           
        var jSonData = new
        {                
            identifier = "Value", 
            label = "Text",
            items = hmodel.ListHuyenTp.ToArray()
        };
        return Json(jSonData);
    }

The struct of json looks like

{
   "identifier": "abbreviation",
   "label": "name",
   "items": [
       { "abbreviation": "AL", "name": "Alabama" },
        ... other 48 states here ...
       { "abbreviation": "WY", "name": "Wyoming" }
    ]
}

Can you help me? Thank you very much.

jeudi 21 avril 2016

Loading Partial view in ajaxified way

I am trying to load a partialview using ajax method. Since I have tried it in past but I dont know why this time it is not loading the content and data. I am wondering that where I am wrong. How can I correct this? please help asap

This is my view having partial view in one of its div named "Add_Group".

@(Html.Kendo().Window()
    .Name("AddEditGroupWindow")
    .Title("Edit Group")
    .Content(@<text><div id="Add_Group" style="display:none; width:100%;">
            @Html.Partial("~/Areas/Admin/Views/UserGroups/_AddGroupPartial.cshtml");
        </div> </text>)
                .Visible(false).Width(1000).Height(300))

After I get data using post as below I am trying to load that patial view using below:

$.post("/UserGroups/getGroupDetail", { "groupId": id }, function (response) {
            $("#Add_Group").html(response.Data);
            $("#AddEditGroupWindow").data("kendoWindow").open();
            $("#Add_Group").show();
        });

in controller it is like below:

 public ActionResult GetGroupDetail(string groupId)
        {
            var data = string.Empty;
            UserGroupRoleModel objmodel = new UserGroupRoleModel();
            var groupEntity = this._userGroupServices.GetGroupDetail(Convert.ToInt32(groupId));
            return this.Json(new { Data = groupEntity });
        }

Whom to continue career with asp.net or asp.net mvc?

Currently, I am working on both asp.net and asp.net MVC in a software company. I just want to know that if I have to choose one of the two in future for job, which should be one? I know MVC is latest but as per job concerns Asp.Net is very common and one can get job easily.

How to disable Select one then disable it's from second in multi select dropdownlist

I'm using multiselect dropdowlist and i want to disable item which is select first dropdown list. I have lots of googling but not see any correct solution which i want.

my code below

<table>
<tr>
    <td>

        <select class="form-control" id="day_list_1" multiple="multiple" name="shift[day_list_1][]">
            <option value="Sunday">Sunday</option>
            <option value="Monday">Monday</option>
            <option value="Tuesday">Tuesday</option>
            <option value="Wednesday">Wednesday</option>
            <option value="Thursday">Thursday</option>
            <option value="Friday">Friday</option>
            <option value="Saturday">Saturday</option>
        </select>

    </td>
    <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </td>
    <td>
        <select class="form-control" id="day_list_2" multiple="multiple" name="shift[day_list_2][]">
            <option value="Sunday">Sunday</option>
            <option value="Monday">Monday</option>
            <option value="Tuesday">Tuesday</option>
            <option value="Wednesday">Wednesday</option>
            <option value="Thursday">Thursday</option>
            <option value="Friday">Friday</option>
            <option value="Saturday">Saturday</option>
        </select>
    </td>
</tr>

<script src="http://ift.tt/1xDNnh9"></script>
<link href="~/Content/jquery.multiselect.css" rel="stylesheet" />
<script src="~/Scripts/jquery.multiselect.js"></script>

<style type="text/css">
    .form-control
    {
        width: 130px;
        height: 130px;
    }
</style>


<script>
    $('select[multiple]').multiselect({
        columns: 1,
        placeholder: 'Select options'
    });

    $(document).ready(function () {

    });
</script>

somthing like this how to disable dropdown options based on the previously selected dropdown values in multi select dropdown?

Creating Cutom RouteBase class

I want to know what is the function of httpContext.Request.AppRelativeCurrentExecutionFilePath in below code. Please, explain how the routing system matches the requested url:

public override RouteData GetRouteData(HttpContextBase httpContext) 
{ 
RouteData result = null; 
string requestedURL = string.Empty; 
for (int i = 0; i < urls.Length; i++) 
{                   
 if(httpContext.Request.AppRelativeCurrentExecutionFilePath.Contains(urls[i])) 
 { 
    requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath; 
    break; 
 } 
}     

if (!string.IsNullOrEmpty(requestedURL)) 
{ 
   result = new RouteData(this, new MvcRouteHandler()); 
   result.Values.Add("controller", "CustomRoute"); 
   result.Values.Add("action", "DirectCustomUrls"); 
   result.Values.Add("customUrl", requestedURL); 
} 
   return result; 
}

mercredi 20 avril 2016

Unable to install website msi using command line in Window10

Overview : Installing a MVC3 Website using C# command line. The application installed correctly in Win7, win8, server 2008 & 2013. The same installer not working in window10 after configure IIS correctly.

Error Message : Product: Web Client -- This setup requires Internet Information Server 5.1 or higher and Windows XP or higher. This setup cannot be installed on Windows 2000. Please install Internet Information Server or a newer operating system and run this setup again.

Error Message in Event log(MsiInstaller) : Windows Installer installed the product. Product Name: Web Client. Product Version: 3.x.xx. Product Language: 1033. Manufacturer: xxxx. Installation success or error status: 1603.

Installer code :

 Process p = new Process();
            p.StartInfo.FileName = msiexec.exe;
            p.StartInfo.Arguments ="/qn /i \"" + Settings.InstallationDirectory + "Website\\WebClient.msi\"";
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.WaitForExit();

unable to see installed website in IIS.

How to pass values from view to controller in Asp.net

So we have this form in Login.cshtml

<form class="form-horizontal" action="LoginTest">
        <div class="form-group">
            <label for="inputEmail" class="col-sm-2 control-label">Gebruikersnaam</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputEmail" placeholder="Email">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword" class="col-sm-2 control-label">Wachtwoord</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="inputPassword" placeholder="Password">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary">Registreer</button>
                <button type="submit" class="btn btn-default">Annuleer</button>
            </div>
        </div>
    </form>

And we have a Logincontroller with the next method LoginTest:

public ActionResult LoginTest(string inputEmail, string inputPassword)
    {
        Response.Write("<script>alert('" + inputEmail + "')</script>");
        return null;
    }

But we are unable to pass the values. Hopefully someone can help us!

mardi 19 avril 2016

Setting up a recurring subscription service for an ASP.NET website

I have an ASP.NET website that is similar to Yellow Pages in functionality and I want to offer a recurring subscription service to users that enables their business profiles to be priority listed, or brought to the top if they are subscribed. Each user has a "SubscriptionLevel" integer tied to their account on the database side and I simply need to modify that field depending on what subscription service they select. Are there any C# libraries out there I can use to set this up quick? I would prefer users to pay through PayPal.

ASP.NET MVC Posting two Actions at once to write multiple entries into two tables

I am building a program in ASP.NET MVC with a database. It is for recipe and ingredient matching in your kitchen, so to speak. It pulls recipes from a database table, and ingredients from another table, related through a junction table.

RecipeTable 
ID PK int not null
RecipeName varchar(25) not null
CategoryID int FK(references Cateogory(ID) not null
Directions varchar(max) not null

and

Recipe_IngredientsTable
RecipeID int FK(references Recipe(ID) not null
IngredientID int FK(references Ingredient(ID) not null (Ingredient table is just IDs and names)
IngredientAmount varchar(25) not null

With a unique constraint set up as RecipeID and IngredientID.

Now, the issue I'm having is with creating a new recipe, and I want to go ahead and save the list of RecipeIngredients at the same time. RecipeDM contains a field for ID, RecipeName, CategoryID, a List, and a field Directions. As it sits right now, on my DAL level, I have this method for writing the recipe:

public void CreateRecipeIngredients(RecipeDM recipe)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            // Building single SQL query statement to reduce trips to database for multiple RecipeIngredients
            StringBuilder queryString = new StringBuilder();
            int rowsAffected = 0;
            foreach (RecipeIngredientDM ingredient in recipe.RecipeIngredients)
            {
                queryString.AppendFormat("Insert into Recipe_Ingredients (RecipeID, IngredientID, IngredientAmount) Values ({0}, {1}, {2});",
                    recipe.RecipeID,
                    ingredient.IngredientID,
                    ingredient.IngredientAmount);
            }
            try
            {
                using (SqlCommand command = new SqlCommand(queryString.ToString(), connection))
                {
                    command.CommandType = CommandType.Text;
                    rowsAffected = command.ExecuteNonQuery();
                }
                logger.LogError("Event", "User was able create a list of ingredients for a recipe.", "Class: RecipeIngredientDAO -- Method: CreateRecipeIngredients");
            }
            catch (Exception e)
            {
                logger.LogError("Error", "User was unable to create a list of ingredients for a recipe, error: " + e, "Class: RecipeIngredientDAO -- Method: CreateRecipeIngredients");
            }
            finally
            {
                if (rowsAffected != recipe.RecipeIngredients.Count())
                {
                    recipeData.DeleteRecipe(recipe);
                }
                logger.LogError("Error", "All RecipeIngredients did not make it into the table; rolling back recipe creation.", "Class: RecipeIngredientDAO -- Method: CreateRecipeIngredients");
                // If the number of RecipeIngredients inserted into the table does not equal the number of ingredients the recipe has, then roll back entire creation of recipe to prevent bad data
            }
        }
    }

And this method for writing the recipe:

        public void CreateRecipe(RecipeDM recipe)
    {
        try
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@RecipeName", recipe.RecipeName)
                ,new SqlParameter("@CategoryID", recipe.CategoryID)
                ,new SqlParameter("@Directions", recipe.Directions)
            };
            dataWriter.Write(parameters, "CreateRecipe");
            logger.LogError("Event", "User was able to create a recipe to the database", "Class: RecipeDAO -- Method: CreateRecipe");
        }
        catch (Exception e)
        {
            logger.LogError("Error", "User was unable to create a recipe to the database, error: " + e, "Class: RecipeDAO -- Method: CreateRecipe");
        }

    }

Model - CreateRecipeVM

public class CreateRecipeVM
{
    public int RecipeID { get; set; }

    [Required]
    [Display(Name = "Recipe Name")]
    [StringLength(25, ErrorMessage = "Please enter a recipe name at least {2} and no more than {1} characters long.", MinimumLength = 3)]
    public string RecipeName { get; set; }

    [Required]
    [Display(Name = "Categories")]
    public List<CategorySM> Categories { get; set; }
    public int CategoryID { get; set; }

    [Required]
    [Display(Name = "Ingredients")]
    public List<RecipeIngredientVM> Ingredients { get; set; }
    public string IngredientAmount { get; set; }

    [Required]
    [Display(Name = "Directions")]
    public string Directions { get; set; }
}

Model - RecipeIngredientVM

public class RecipeIngredientVM
{
    public int RecipeID { get; set; }
    public int IngredientID { get; set; }

    [Required]
    [Display(Name = "Ingredient Name")]
    public string IngredientName { get; set; }

    [Required]
    [Display(Name = "Quantity")]
    public string IngredientAmount { get; set; }
}

Now, I'm almost sure I've got the CreateRecipeIngredients method written correctly, but I'm not sure. And I know this is a bit of a long-winded post, but I promise, once I get the foundation laid out, I will explain what my issue is.

On my Recipe controller, I have for Create Recipe:

 // GET: Recipe/Create
    public ActionResult Create()
    {
        CreateRecipeVM recipe = new CreateRecipeVM();
        recipe.Categories = catLog.GetAllCategories();
        recipe.Ingredients = Mapper.Map<List<RecipeIngredientVM>>(ingLog.GetAllIngredients());            
        return View(recipe);
    }

    // POST: Recipe/Create
    [HttpPost]
    public ActionResult Create(CreateRecipeVM recipe, List<RecipeIngredientVM> ingredients)
    {
        try
        {
            TempData["NewRecipeID"] = recipe.RecipeID;                
            recipe.Ingredients = (List<RecipeIngredientVM>)TempData.Peek("NewRecipeIngredients");
recLog.CreateRecipe(Mapper.Map<RecipeSM>(recipe));
            recIngLog.CreateRecipeIngredients(Mapper.Map<RecipeSM>(recipe));
            return RedirectToAction("Details", new { id = recipe.RecipeID }); ;
        }
        catch
        {
            return View();
        }
    }

My Create view for recipe is as follows:

@model MyKitchen.Models.CreateRecipeVM
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 <h3>Add a New Recipe</h3>

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

<div class="form-horizontal">

    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.RecipeID)

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

    <div class="form-group">
        @Html.LabelFor(model => model.Categories, htmlAttributes: new { @class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.DropDownList("CategoryID", new SelectList(Model.Categories, "CategoryID", "CategoryName"), "--- Select A Category ---")
        </div>
    </div>

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

    <div class="form-group">
        @Html.LabelFor(model => model.Ingredients, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <button type="button" name="AddIngredients" id="showPartial" class="btn btn-default">Click here to add ingredients for this recipe</button>
            <div id="partialView"></div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

When you click the button named "AddIngredients" with the id of "showPartial", it renders in a PartialView in the respectively named Div right below it. My jquery for that works fine, after many hours of trying to figure that one out (did I mention I'm new to this?).

Now, farther down in my RecipeController, I have the following method, which is on that partial view:

// GET Recipe/CreateIngredientsForRecipe
        public ActionResult CreateIngredientsForRecipe()
        {
            List<RecipeIngredientVM> ingredients = Mapper.Map<List<RecipeIngredientVM>>(ingLog.GetAllIngredients());
        return View(ingredients);
    }

    // POST Recipe/CreateIngredientsForRecipe
    [HttpPost]
    public ActionResult CreateIngredientsForRecipe(List<RecipeIngredientVM> ingredients)
    {
        List<RecipeIngredientVM> recIngredients = new List<RecipeIngredientVM>();
        foreach(RecipeIngredientVM food in ingredients)
        {
            RecipeIngredientVM recFood = new RecipeIngredientVM();
            if(food.IngredientAmount != null)
            {
                recFood.RecipeID = (int)TempData.Peek("NewRecipeID");
                recFood.IngredientID = food.IngredientID;
                recFood.IngredientName = food.IngredientName;
                recFood.IngredientAmount = food.IngredientAmount;
                recIngredients.Add(recFood);
            }
        }
        TempData["NewRecipeIngredients"] = recIngredients;
        return RedirectToAction("Details", new { id = recIngredients[0].RecipeID }); ;
    }
}
}

And the partial renders in correctly, and that CreateIngredientsForRecipe.cshtml is:

<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.IngredientName)
    </th>
    <th>
        @Html.DisplayName("Is it in your kitchen?")
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.IngredientName)
    </td>
    <td>
        @Html.EditorFor(modelItem => item.IngredientAmount)
    </td>
</tr>
 }
<tr>
    <td>@Html.ActionLink("Don't see the ingredients you need?  Click here to add them to the ingredient database!", "Create", "Ingredient")</td>
</tr>

Now, my problem. When I click the Create button at the bottom of the page, I want it to fire off the action and methods for CreateRecipe, as well as for CreateRecipeIngredients. I'm not sure how to do this, but I've written what I have so far, and this is what is currently in my code. I don't remember what all I've tried, but right now, the exception it's shooting back at me is

User was unable to create a list of ingredients for a recipe, error: System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
   at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at DAL.RecipeIngredientDAO.CreateRecipeIngredients(RecipeDM recipe) in C:\Users\Sabba\Documents\Visual Studio 2015\Projects\MyKitchen\DAL\RecipeIngredientDAO.cs:line 73

I've spent almost a full 20 hours in the past two days trying to get this thing to work, but to no avail. I've gotten almost the entire rest of the project done, except for this one thing, and it is driving me absolutely bonkers.

Can someone PLEASE point me in the write direction to make this work the way I want it to, or at least the way it NEEDS to?

lundi 18 avril 2016

Out of memory issue in IE

I have widgets(charts and tables) in our application(MVC3). I am giving an option to download all widgets in ppt format like each widget as a slide in ppt. Using the canvas, converting the widget into an image and making it as a slide. The problem here is it downloads properly in Chrome and Firefox but not in IE. In IE it gives 'out of memory' exception in the client side. There are no infinite loops in my code.

I have tried following links but didn't work: http://ift.tt/1rdmAaK

and http://ift.tt/1XFXGu8

Any help would be appreciated.

Unable to pass routing values from jquery to mvc action method

JavaScript

<script type="text/javascript">
        $(function () {

          $("[ID*=btnAdd]").click(function () {
//Here I am passing routing value i.e student 
            var url = '@Url.Action("GetPV", "Home", new { students=Model.Students })';

            $('#grid1').load(url);
          });

        });

HTML

<div id="grid1"></div>
    <input type="button" id="btn" Value="Submit"/>

MVC Action

//Here iam getting students parameter as null

public ActionResult GetPV(List<Student> students)
        {
            students.Add(new Student());

            StudentModel objstudentmodel = new StudentModel();


            objstudentmodel.StudentList = students;

            return PartialView("_DemoPV", objstudentmodel);

        }

Model

public class StudentModel
    {
        public List<Student> StudentList { get; set; }

    }

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

        public string Name { get; set; }

        public string Mobile { get; set; }

        public string Email { get; set; }

        public string Nationality { get; set; }

        public List<HttpPostedFile> files { get; set; }

    }

I want to load the partial view through jquery on button click event.

In this scenario, I want to pass student list as parameter to action method.

Here I am not able to pass the routing values from jquery URL Action to the MVC Action method.

Please assist me to resolve the issue. Thanks.

dimanche 17 avril 2016

Add view page in to a telerik tab in asp.net mvc3

I am having 2 problems using tabstrip.

  1. I want to add view-page or telerik grid into telerik tab coming from database (image).
  2. i am having 2 tabs in a view (Tab1 & Tab 2) how can i add onclick action on tab selection (means swapping tabs) without reloading page

Below code show adding content but how can i add view page or partial view

@(Html.Telerik().TabStrip().Name("tab").Items(items =>


    {
        iitems.Add().Text("Tab 1").Content("Test Tab 1");
        items.Add().Text("Tab 2").Content("Test Tab 2");
    }))

Drop Downs not passing data to controller

I have set up a modal with a form to pass data into my controller like so.

<div class="container">
<div class="modal fade" id="modalcreate" tabindex="-1" role="dialog" aria-labelledby="createGroup" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
                <h4 class="modal-title text-center">Create a New Instance</h4>
            </div>

            <div class="modal-body" style="text-align: center">
                <div class="row">
                    <div class="modal-body" style="text-align: center">
                        <form action="/Home/CreateInstance/" method="POST">
                            <div class="form-group">
                                <label for="amiId">AMI ID:</label>
                                <select class="form-control text-center" id="amiId" style="margin: 0 auto">
                                    <option>ami-8519a9f6</option>
                                    <option>ami-8b8c57f8</option>
                                </select>
                                <label for="keyPairName">Key Pair Name:</label>
                                <input name="keyPairName" class="form-control text-center" type="text" placeholder="Conners Key" style="margin: 0 auto">
                                <label for="instanceType">InstanceType:</label>
                                <select class="form-control text-center" id="instanceType" style="margin: 0 auto">
                                    <option>InstanceType.T1Micro</option>
                                </select>
                                <label for="minCount">Minimum Instance Number:</label>
                                <input name="minCount" class="form-control text-center" type="text" placeholder="1" style="margin: 0 auto">
                                <label for="maxCount">Maximum Instance Number:</label>
                                <input name="maxCount" class="form-control text-center" type="text" placeholder="1" style="margin: 0 auto">
                                <label for="groups">Security Groups Attached:</label>
                                <select class="form-control text-center" id="groups" style="margin: 0 auto">
                                    @foreach (var groups in Model.groups)
                                    {
                                    <option>@groups.GroupName</option>
                                    }
                                </select>            
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-success btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Create</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

but for some reason, the method in the controller is only receiving the textbox data. According to W3 bootstrap inputs I have set them up correctly http://ift.tt/1jCqRj9

Can someone please tell me what I seem to be missing?

.Net MVC 3 403.14 error

I'm creating an asp.net MVC3 demo application. I have attached the application with this thread. I'm facing a HTTP Error 403.14 - Forbidden enter image description hereissue when trying to run the application. The issue occurs only in a specific scenario. i.e. in the RegisterRoutes method in the global.asax has only the below code then the issue occurs.

 routes.MapRoute(
                "Process1", // Route name
                "Process/List" // URL with parameters
            );

If we have the above code with default route the application works fine without any issues. The issue occurs when i have this particular code alone in the register routes method. I tried the solutions given in this link but it did not work. I assume the issue with that code. If yes then please let me know what causes the issue. I use windows 8.1 & the iis is 8.5. The code can be found here

Unable to add record to a table that having more than one relation with other tables

The code is written in ObjectContext. I've tried max to sort this.

tbluserprofiles.Id = (short)DataAccess.tblUserProfiles.NextID(db);

tbluserprofiles.Base.Active = true;
tbluserprofiles.Base.Status = clsSettings.Status.NEW;

tbluserprofiles.Base.CreatedBy = new Inventory365_MVC.Controllers.AccountController().LoginInfo.tbluser.Id;
tbluserprofiles.Base.ModifiedBy = new Inventory365_MVC.Controllers.AccountController().LoginInfo.tbluser.Id;
tbluserprofiles.Base.CreatedDate = DateTime.Now;
tbluserprofiles.Base.ModifiedDate = DateTime.Now;

//DataAccess.tblUserType tblUserTypes = db.tblUserTypes.Single(t => t.Id == tbluserprofiles.tblUserType.Id);
//DataAccess.tblCompanyProfile tblCompanyProfiles = db.tblCompanyProfiles.Single(t => t.Id == tbluserprofiles.tblCompanyProfile.Id);

db.AcceptAllChanges();
//tblUserTypes.tblUserProfiles.Add(tbluserprofiles);
//tblCompanyProfiles.tblUserProfiles.Add(tbluserprofiles);
//tbluserprofiles.tblCompanyProfile = tblCompanyProfiles;
//tbluserprofiles.tblUserTypes = tblUserTypes;
//db.tblUserProfiles.AddObject(tbluserprofiles);

db.tblUserTypes.Where("it.Id = @Id", new ObjectParameter("Id", tbluserprofiles.tblUserType.Id)).Execute(MergeOption.AppendOnly).First().tblUserProfiles.Add(tbluserprofiles);
db.tblCompanyProfiles.Where("it.Id = @Id", new ObjectParameter("Id", tbluserprofiles.tblCompanyProfile.Id)).Execute(MergeOption.AppendOnly).First().tblUserProfiles.Add(tbluserprofiles);

//db.AddTotblUserProfiles(tbluserprofiles);
//db.tblUserTypes.Single(t => t.Id == tbluserprofiles.tblUserTypes.Id).tblUserProfile.Add(tbluserprofiles);
//db.tblCompanyProfiles.Single(t => t.Id == tbluserprofiles.tblCompanyProfile.Id).tblUserProfiles.Add(tbluserprofiles);
//db.AcceptAllChanges();

db.SaveChanges();

vendredi 15 avril 2016

DateTime parses differently when passed via HTTP-POST in body and via HTTP-GET as query params

On our MVC 3 Web Application we define the Thread.CurrentThread.CurrentCulture with the current user's preferences. However, in one View we submit the data via Ajax always in the format mm/dd/yyyy this works fine as long as the user's culture is en_US. (obviously)

The surprising thing, it works for all users, when we pass it as HTTP-POST, but stops working when we pass it as HTTP-GET. (In both cases, the exact same value is leaving the browser).

Any ideas why HTTP-POST calls would be handled differently than HTTP-GET?

Also, there are other parameters to that action. In case of an HTTP-POST, they are all set in the body like:

{
  "date": "04/15/2016",
  "someText": "Hello World",
  "someNumber": 42
}

and for HTTP-POST they are query parameters instead:

http://ift.tt/23AEyF8

jeudi 14 avril 2016

how to Integrate Paypal module using Angularjs asp.net mvc?

i am create small shopping cart demo and integrate the paypal module in angularjs with asp.net mvc..but i am not get the perfect result..i have tried the below code in my small shopping cart demo..then i have get the error your shopping cart is empty.. this is my controller method..

   public ActionResult ValidCommand(AddToCart Cart)
    {
        var userid = Convert.ToInt32(CookieHelper.GetCookieValue(CookieKeys.UserID));
        bool useSandBox = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSendBox"]);
        var paypal = new payPalMode(useSandBox);

        List<AddToCart> c_list = new List<AddToCart>();
        var carts = from c in db.AddToCarts
                    join p in db.tblProducts
                    on c.ProductId equals p.ProductId
                    where (c.UserId == userid)
                    select new
                    {
                        cid = c.CartId,
                        pprice = p.Price,
                        pid = p.ProductId,
                        pname = p.ProductName,
                        pdesc = p.Descripation,
                        img = p.Image,
                        qun = c.Quantity
                    };
        foreach (var item in carts)
        {
            AddToCart ctbl = new AddToCart();
            ctbl.CartId = item.cid;
            ctbl.Quantity = item.qun;
            ctbl.ProductId = item.pid;
            ctbl.productName = item.pname;
            ctbl.Descripation = item.pdesc;
            ctbl.price = item.pprice;
            ctbl.Image = item.img;
            c_list.Add(ctbl);
        }
        paypal.CartList = c_list;
        return View("ValidCommand", paypal);
    }

this is my paypal.cs class

public class payPalMode
{
    public string cmd { get; set; }
    public string business { get; set; }
    public string no_shipping { get; set; }
    public string @return { get; set; }
    public string cancel_return { get; set; }
    public string notify_url { get; set; }
    public string curreny_code { get; set; }
    public string actionUrl { get; set; }
    public string Cart { get; set; }
    public string upload { get; set; }

    public List<AddToCart> CartList = new List<AddToCart>();

    public payPalMode(bool useSandBox)
    {
        this.cmd = "_cart";

        this.business = ConfigurationManager.AppSettings["business"];
        this.cancel_return = ConfigurationManager.AppSettings["cancel_return"];
        this.@return = ConfigurationManager.AppSettings["return"];
        useSandBox = true;
        if (useSandBox)
        {
            this.actionUrl = ConfigurationManager.AppSettings["test_url"];
        }
        else
        {
            this.actionUrl = ConfigurationManager.AppSettings["Prod_url"];
        }
        this.notify_url = ConfigurationManager.AppSettings["notify_url"];
        this.curreny_code = ConfigurationManager.AppSettings["currency_code"];
        this.upload = ConfigurationManager.AppSettings["upload"];
        this.no_shipping = "1";
    }
}

this is my angularjs funaction..

$scope.checkout = function () {
    debugger;
    var getdata = AngularService.checkout();
    debugger;
    getdata.then(function (data) {
        debugger;
        $rootScope.item = data;

    })
};

this is my view..

<body>
<div ng-app="MyApp" ng-controller="AddToCart">
<form id="hiddenform" action="@Model.actionUrl">
    @Html.HiddenFor(model => model.cmd)
    @Html.HiddenFor(model => model.business)
    @Html.HiddenFor(model => model.no_shipping)
    @Html.HiddenFor(model => model.@return)
    @Html.HiddenFor(model => model.cancel_return)
    @Html.HiddenFor(model => model.notify_url)
    @Html.HiddenFor(model => model.curreny_code)
    @Html.HiddenFor(model => model.upload)
    @{
        var count = 1;

        foreach (var item in Model.CartList)
        {
            string name = "item_name" + count;
            string amount = "amount" + count;

            <input type="hidden" name="@name" value="@item.productName" />
            <input type="hidden" name="@amount" value="@item.price" />

            count++;
        }
    }
</form>
<h2>Connect To PayPal</h2>
</div>

this above code i have tried and get the error your shopping cart is empty.so please any one idea about it so please tell me...

Get Form data from the input fields Which names are generated by model dynamically into the controller

I have a controller as given below

[HttpPost]
    public ActionResult LoginResult()
    {
        //want get the data here
        return View();
    }

and I have a view in which I am rendering a view by using a model as given below

@model IEnumerable<My.Models.SurveyData>
@{
    ViewBag.Title = "Index";
}

<h2>Survey Form</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    @using (Html.BeginForm("LoginResult", "My"))
    {        
        foreach (var item in Model)
        {
            <tr>
                <h4> @Html.DisplayFor(modelItem => item.Question)</h4>
                <br />

            @if ((int)item.InputType == 1)
            {

                <input type="text" id="@item.Id" name="@item.Id" value="" />
            }
            else if ((int)item.InputType == 2)
            {
                <textarea rows="4" cols="50" id="@item.Id" name="@item.Id"></textarea>
            }
            else if (item.InputType.ToString().Trim().ToLower() == "checkbox")
            {
                for (int i = 0; i < @item.NumberOfChoice; i++)
                {
                    <input type=@item.InputType.ToString().Trim().ToLower() name="@item.AdminAnswers.ElementAt(i).Answer"></input>@item.AdminAnswers.ElementAt(i).Answer
                    <br />
                }
            }

        }
    <input type="submit" value="Login" />
}

Now I want to get All the input fields value on form submission into the LoginResult Method which is in Controller named "My",but all the input fields name will come dynamically. so how can I get this values in the method.

mardi 12 avril 2016

OleDb Read Excel not working after to publish to IIS. I can't catch the cause of the error on ASP.Net MVC 3

I am using Microsoft.ACE.OLEDB.12.0; i tried to read 2007 excel file and it won't work. It only works on excel 2003. Now, I'm having a problem that after i publish to IIS on the same unit that i use for the development now it won't work. I am using ajaxupload.js to get the excel file.

These are my source code:

public void ReadfileBilling()
        {
            HttpPostedFileBase file = Request.Files[0];
            string nm = file.FileName;
            MemoryStream ws = new MemoryStream();
            var imageBytes = ws.ToArray();
            if (file != null && file.ContentLength > 0)
            {


                var uploadedFile = Request.Files[0];
                var fileName = Path.GetFileName(file.FileName);
                var fileSavePath = "";
                //var path = Server.MapPath("../App_Data/");
                var path = Server.MapPath("~/App_Data/");
                fileSavePath = Server.MapPath("~/App_Data/" + fileName);
                uploadedFile.SaveAs(fileSavePath);

                var Indexof = fileName.IndexOf(".");
                var FileExtension = fileName.Substring(Indexof + 1);
                var len = file.ContentLength;
                var type = file.ContentType;

                String File1 = file.FileName;
                FileStream t1 = new System.IO.FileStream(fileSavePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                StreamReader readFile = new System.IO.StreamReader(t1);

                Importexcel(path, fileName);
            }

        }

public ActionResult Importexcel(string path, string filename)
        {
            string path1 = string.Format("{0}/{1}", path, filename);
            string sqlConnectionString = @"Data Source=GWXPROG\SQL_2k8;Initial Catalog=GeoPIMS;Integrated Security=false; user id=sa; password=P@ssw0rd;";


            string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
            //Create Connection to Excel work book
            OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
            //Create OleDbCommand to fetch data from Excel
            OleDbCommand cmd = new OleDbCommand("Select [PolicyNo], [BPNO],[PS], [GS], [EC], [CONSOLOAN], [ECARDPLUS],  [SALARY_LOAN],[CASH_ADV],   [EMRGYLN], [EDUC_ASST], [ELA], [SOS], [PLREG], [PLOPT], [REL], [LCH_DCS], [STOCK_PURCHASE], [OPT_LIFE], [CEAP], [EDU_CHILD], [GENESIS], [GENPLUS], [GENFLEXI],[GENSPCL] from [Sheet1$]", excelConnection);

            excelConnection.Open();
            OleDbDataReader dReader;
            dReader = cmd.ExecuteReader();

            SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
            //Give your Destination table name
            sqlBulk.DestinationTableName = "PAYROLL.GSISBilling";
            sqlBulk.WriteToServer(dReader);
            excelConnection.Close();


            return RedirectToAction("Import");
  }

Bootstrap for ASP Populate table from txt file

I've been trying to populate a table made using Bootstrap for ASP from a txt file but it seems I keep getting stuck on doing it... I'll leave below my attempt so you can take a look at it and perhaps help me out. The format used in the txt file is the following:

Column1Txt Column2Txt Column3Txt Column4Txt
Column1Txt Column2Txt Column3Txt Column4Txt
Column1Txt Column2Txt Column3Txt Column4Txt
Column1Txt Column2Txt Column3Txt Column4Txt

Here's my attempt of doing it:

<div class="container">
            <div class="left">
                <div class="row">
                    <table class="table table-striped">
                        <!-- table head -->
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Column1</th>
                                <th>Column2</th>
                                <th>Column3</th>
                                <th>Column4</th>
                            </tr>
                        </thead>
                    </table>
                    <iframe src="/tablecontent/content.txt" frameborder="0"></iframe>
            </div>
        </div>
   </div>

I know it's not even inside the table but I've also tried to do it with it inside the table and it didn't work properly as well.

Thanks for your time in advance.

How to exclude a js file from a view- asp.net mvc

I'm developing an asp.net mvc application in which I use a _Layout file to contain all references of js files and css file. But I have only one view which I need to exclude a js file from it's references. What I can do is I dont put this file on _Layout and manually put it on all views except the view mentioned above. But I think it's too cumbersome. Is there any better approach to solve this issue?

lundi 11 avril 2016

html helper link not working in ie

I have the following html code:

 <div class="main">
   <div class="container">
     <button class="btn btn-default">
        @Html.ActionLink("Explore", "Explore")
    </button>
    </div> </div>

The button is styled as below:

.main .btn{
 margin-left:600px;
-moz-transition: box-shadow 0.5s;
-o-transition: box-shadow 0.5s;
-webkit-transition: box-shadow 0.5s;
transition: box-shadow 0.5s;
background: transparent;
border:1px solid #7b278e;
}
.main .btn a{
    color:#7b278e;
    text-decoration:none;
 }

.main .btn:hover{
    box-shadow:3px 3px 6px #7b278e;
    font-weight:600;
    border:1px solid #7b278e;
 }

The link works fine in chrome, but not in IE. Ive not much idea about browser compatibility. Plz help!

setExpressCheckout returning token empty

SetExpressCheckout Returns null into token object ?

Got one solution but seems not a permanent answer. Please suggest?

modify "Any" property in reference.vb From

[System.Xml.Serialization.XmlElementAttribute(Order=6)]

with

[System.Xml.Serialization.XmlIgnoreAttribute()]

samedi 9 avril 2016

Redirect to Login Page if Image not found MVC 4

I am stuck into very strange situation where my MVC 4 Application is throwing at login page(account/login) if image with its directory path is not found in my project.

HTML Helper Method:

public static MvcHtmlString GetTemplateThumgImgPath(this System.Web.Mvc.HtmlHelper helper, string ImageName)
    {
        string staticpath = VirtualPathUtility.ToAbsolute("~/content/templates/");
        return (new MvcHtmlString(staticpath + ImageName));
    }

View:

        <ul>
            @foreach (var o in Model.ObjTemplateList)
            {
                <li>
                    <img src="@Html.GetTemplateThumgImgPath(string.Concat(o.Directory, "/", o.ThumbImage))" width="50px" height="50px" />
                </li>                        
            }
        </ul>

Web Config:

<customErrors mode="On"  defaultRedirect="~/Error/PageNotFound">
  <error statusCode="404" redirect="~/Error/PageNotFound"/>
</customErrors>

Now if the directory + image does not exists in my project then it throws to login page every time i request to any other controller binded with authorize attribute. I have tested it by removing my HTML helper method from image src, then everything works.

Also, Magically when i update Custom error mode to Off then still this issue does not arise. /content/templates/ is my base directory where many template folders can be created at run time.

Is something i missed? Pls help

vendredi 8 avril 2016

form.searialize does not post few hidden fields

I have below view model:

public class TasksViewModel
{
    public TasksViewModel()
    {
         Status = new SelectList(Enumerable.Empty<SelectListItem>());
         TaskID = 0;
         TaskDate = DateTime.Today;
         StatusID = "1";
    }

    public int TaskID { get; set; }

    [Required(ErrorMessage = "Date is required")]
    public DateTime TaskDate { get; set; }

    public string AssignedBy { get; set; }

    [StringLength(1000, ErrorMessage = "Maximum limit reached")]
    [Required(ErrorMessage = "Description is required")]
    public string TaskDescription { get; set; }

    [Required(ErrorMessage = "Please select an user")]
    public int UserId { get; set; }
    public SelectList Users { get; set; }
    public string UserName { get; set; }

    [StringLength(1000,ErrorMessage="Maximum limit reached")]
    public string AdditionalNotes { get; set; }

    [Required(ErrorMessage = "Please select a status")]
    public string StatusID { get; set; }
    public SelectList Status { get; set; }
    public string StatusStr { get; set; }
}

and have below view for editing

@using (Html.BeginForm("AddEditUser", "Admin", FormMethod.Post, new { id = "frmNotes"}))
{
     @Html.AntiForgeryToken();
     <div style="float:right">
          @Html.DropDownListFor(m => tasks.StatusID, tasks.Status, "Please select a Status", new { @class = "selectpicker" })
          @Html.ValidationMessageFor(m => tasks.StatusID)
     </div>
     @Html.HiddenFor(m => tasks.TaskID);
     @Html.HiddenFor(m => tasks.TaskDate);
     @Html.HiddenFor(m => tasks.UserId);
     @Html.HiddenFor(m => tasks.TaskDescription);
     @Html.TextAreaFor(m => tasks.AdditionalNotes, htmlAttributes: new { placeholder = "Enter additional notes", @class = "form-control materialize-textarea", style = "padding:1.6rem 0; min-height:3rem", length = 1000 })
     <button data-href="@Url.Action("AddEditTask", "Admin")"><i class="material-icons">update</i></button>
}

In my view, I have multiple hidden fields for different model data which I post along with form to overcome ModelState validation and I do not want this data to be edited. But out of above 4 hidden fields only 2 gets posted i.e. tasks.TaskID and tasks.TaskDate but not other 2 i.e. tasks.UserId and tasks.TaskDescription. I use form.serialize to post the values on button click as below:

var _form = _elem.closest('form');
if (_form.valid()) {
     var formdata = _form.serialize();
     var request = $.post(_url, formdata);
     request.complete(function (response) {
           if (response.responseJSON.result) {
               Materialize.toast(response.message, 5000, 'rounded');
           } else {
               Materialize.toast(response.message, 5000, 'rounded')
           }
     }).error(function () {
           Materialize.toast("Something went wrong on our side!", 5000, 'rounded')
     })
}

and here is my controller signature

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddEditTask(TasksViewModel m)

When I do a quick watch on m above, this is what it looks like.

Test Image

I did a console.log on formdata and I can see the values there..

__RequestVerificationToken=XdsadgBZ657qNyDbq6KPadasdaye9u4f9wAX0JLtbhfuYTbykensxVCm_zSzevnUCfE6t2sXSYbhoLekHZ8damvfFOCPGRGWCo98adas7da7dhqBY4tjNt2i4JUds3s8dxwvRQN6BoyvSv1Ed454dada9KaknOpz0oTNNnfHqadGajszGh-_rXQuNe4k1&tasks.StatusID=2&tasks.TaskID=1003&tasks.TaskDate=4%2F8%2F2016+12%3A00%3A00+AM&tasks.UserId=1002&tasks.TaskDescription=Test+Task+2&tasks.AdditionalNotes=Test

and as you can see all the hidden fields are included.. Where this will be lost.. Why this will not be received in controller parameter? Any helps or insights appreciated.

jeudi 7 avril 2016

What do I replace IUnityContainer.Registrations.ToList() with?

I was recently given an application to support. It was in MVC3 using NHibernate and Unity along with a host of other packages. In upgrading to MVC5, I update all the packages to their latest version. The problem now is that Unity dropped a couple of properties/methods from the IUnityContainer. I am wondering how do I replace these lines of codes to get my code to compile again?

IUnityContainer.Registrations.ToList()

and

IUnityContainer.IsRegistered(serviceType)

IUnityContainer of course is defined as an IUnityContainer object and I am not trying to use the type directly.

I cannot find anything online about what to replace these with. I see from Microsoft that these methods have been deprecated, but no reason why they have been deprecated.

How is routing done in ASP.NET MVC?

protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}

In MvcApplication class, we call the RegisterRoutes method inside Application_Start method.Where do we create the object of RouteConfig class in the MvcApplication class so that RegisterRoutes is called?

MVC MaxJsonLength error returning a view

i'm getting an error when I return a View in MVC. this error is Error during serialization or deserialization using the JSON JavaScriptSerializer. I already set the MaxJsonLength property in my webconfig and the error is still there.

<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="2147483644"/>
        </webServices>
    </scripting>
</system.web.extensions>

I see a lot of answers in another questions, but the solution i saw is that you can return a JsonResult and at this point change the MaxJsonLength in the variable. but the problem is that im returning a View, and i can't find an answer to this.

I'm using MVC3 with framework 4.5.2. the controller consults the data from another project in solution where i have my business logic, its just a library project.

Enum Condition in Linq Query in C#

I want to add Enum Condition in Linq Query even if Enum datamember is null or empty

I had added ALL in model for Filter purpose so that if user select ALL then all data should be displayed

Web Screen

Data Model :

    public partial class AuditTable
    {
        public int ID { get; set; }
        public int CompanyId { get; set; }
        public int KeyFieldID { get; set; }
        public System.DateTime DateTimeStamp { get; set; }
        public EntityType DataModel { get; set; }
        public string ValueBefore { get; set; }
        public string ValueAfter { get; set; }
        public string Changes { get; set; }
        public AuditActionType AuditActionTypeENUM { get; set; }

        public int EmployeeId { get; set; }
        public string EmployeeCode { get; set; }
        public string Remarks { get; set; }
        public string IPAddress { get; set; }
        public string UserName { get; set; }
    }
 public enum AuditActionType
    {
        All = 1,
        Create,
        Update,
        Delete
    }

    public enum EntityType
    {
        All = 1,
        BasicDetails,
        EmployeeDetails,
        PersonalDetails                
    }

Below code is working fine but had to repeat same query 4 times. I want to combine below query into one

if (eType == EntityType.All)
 if (aType == AuditActionType.All)
  AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList(); 
 else
  AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.AuditActionTypeENUM == aType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList(); 
else
if (aType == AuditActionType.All)
 AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.DataModel == eType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList();
else
 AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.AuditActionTypeENUM == aType && s.DataModel == eType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList();