jeudi 30 avril 2015

How to assign roles from helper class,MVC5

I am doing something like in action(Get),

[Authorize(Roles = SmartRoles.smclientadmin,SmartRoles.smclientbranchadmin)]
public ActionResult Index()
{
        return View();
}

And Helper Class

public class SmartRoles
{
public static string smclientadmin 
{ get { return smclientadmin; } 
set { smclientadmin = "SMClientAdmin"; } }

public static string smclientbranchadmin 
{ get { return smclientbranchadmin; } 
set { smclientbranchadmin = "SMClientBranchAdmin"; } }

public static string smclientoperator 
{ get { return smclientoperator; } 
set { smclientoperator = "SMClientOperator"; } }    
}

Error its giving is "name attribute argument expected".... Is there a right way to use this method?? If so please help...thanks for your time...

CKFinder.Connector.ConnectorException when uploading file in ASP.NET project

I have taken over an ASP.NET MVC3 project which incorporates ckfinder with ckeditor. This application has been in production for several years and has been fully function.

It was migrated to a new server and now I am receiving the following exception when attempting to upload a file using ckfinder:

Server Error in '/' Application.

Exception of type 'CKFinder.Connector.ConnectorException' was thrown. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: CKFinder.Connector.ConnectorException: Exception of type 'CKFinder.Connector.ConnectorException' was thrown.

Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ConnectorException: Exception of type 'CKFinder.Connector.ConnectorException' was thrown.]
CKFinder.Connector.Connector.OnLoad(EventArgs e) +1378
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34248

I am able to browse the server using ckfinder and add a link to an existing file, rename, and delete files, however, I get this exception when trying to upload a new file. The config.ascx file is configured correctly and I have granted full permissions to Everyone on all related directories. I have googled this exception and there is very little information about it. Any help is appreciated.

maintain a 10 mins channel between WCF and asp.net

please give me suggestions. I have a call to asp.net, and my business logic will call my WCF backend, my WCF takes 10 mins to response. What's the best practice to do this? Is the WCF bi-direction channel the best choice for this? Thanks in advance.

MVC route returns 401 only if ReturnUrl parameter is in querystring

Within an MVC application, we're using a querystring parameter called ReturnUrl to track where the user came from, and where they return to after they finish with the current page/view. In addition, this same parameter is used when their session times out (for instance) and they are sent to the login page with the ReturnUrl parameter now containing the page they were just on.

The login redirect is handled correctly as long as the URL they're coming from does not include the ReturnUrl parameter. But if it does, then they are shown a hard 401 from IIS.

Example 1:

  1. User is on http://ift.tt/1GJfQ6J
  2. Session times out, then user hits refresh.
  3. User is brought to login page with querystring parameter ReturnUrl properly set. GOOD

Example 2:

  1. User is on http://ift.tt/1OJaW0H
  2. Session times out, then user hits refresh.
  3. User is immediately shown IIS' 401 error page instead of being sent back to the login page. BAD

Note that the request is making it to the MVC handler:

WHY ME?!

I've debugged as best I can but the issue appears to occur within the MVC framework itself. If I change the ReturnUrl parameter to something else, ReturnUrl2 for example, then the login redirect works fine.

What's so special about the word ReturnUrl?

Which one use More space a static object or normal class object?

which one is utilize more space in Memory but did't get any sufficient answer please help me .

public class A { public void Get(int x) { }

    public static void Get(int x, int y)
    {
    }
}
class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        a.Get(10);
        A.Get(10, 10);
    }
}

The entity type OrderedEnumerable'2 is not part of the model for the current context

I am getting. The entity type OrderedEnumerable'2 is not part of the model for the current context. when trying to save.

The error is occurring at

await Repository.AddAsync(containers);

HERE IS MY MODEL

public partial class RoadSample
{
    public RoadSample(bool generateContainers = false)
    {
        if(generateContainers)
        {
            GenerateContainers();
        }
    }

    public List<JobContainer> Containers { get; set; }

    public IOrderedEnumerable<JobContainer> GetUsedContainers()
    {
        return from t in Containers
            where t.IsUsed
            orderby t.RTWTankType, t.ContainerSequenceNo
            select t;
    }

    public string ToDescriptionString()
    {
        var regNumbers = new[]
        {
            RegistrationNumber1,
            RegistrationNumber2,
            RegistrationNumber3
        }
            .Where(r => !string.IsNullOrWhiteSpace(r));

        return string.Format("RTW ({0})", string.Join(",", regNumbers));
    }

    public string ToTankListString()
    {
        var tankList = new StringBuilder();
        short? currentTankType = -1;  // RTWTankType will be between 1 and 3

        foreach(var container in GetUsedContainers())
        {
            if(container.RTWTankType != currentTankType)
            {
                if(currentTankType != -1)
                {
                    // the tank is finished, so add the tank delimiter
                    tankList.Append(" / ");
                }
                currentTankType = container.RTWTankType;
            }
            else if(tankList.Length > 0)
            {
                // compartments are separated by comma's
                tankList.Append(",");
            }
            tankList.Append(container.ContainerAlias);
        }
        return tankList.ToString();
    }

    void GenerateContainers()
    {
        // 1-based!! 
        Containers = new List<JobContainer>();
        for(short tankType = 1; tankType <= 3; tankType++)
        {
            for(var compartmentNumber = 1; compartmentNumber <= 10; compartmentNumber++)
            {
                Containers.Add(new JobContainer
                {
                    TankTypeID = 4, // RTWTank
                    RTWTankType = tankType,
                    ContainerSequenceNo = compartmentNumber,
                    ContainerNumber = "Compartment " + compartmentNumber,
                    ContainerAlias = "Compartment " + compartmentNumber
                });
            }
        }
    }

HERE IS MY CONTROLLER

public class JobsController : JmsController<JobsContext>
{
    [Route("{register}")]
    public async Task<List<JobHeader>> Get(Registers register)
    {
        var user = await GetApplicationUserAsync();

        switch(register)
        {
            case Registers.Pending:
                return await Repository.Context.Fn_JobsGetPending(user.BranchID).GetNonTrackedListAsync();
            case Registers.Testing:
                return await Repository.Context.Fn_JobsGetTesting(user.BranchID).GetNonTrackedListAsync();
            case Registers.Inspections:
                return await Repository.Context.Fn_JobsGetInspections(user.BranchID).GetNonTrackedListAsync();
            case Registers.Sampling:
                return await Repository.Context.Fn_JobsGetSampling(user.BranchID).GetNonTrackedListAsync();
            default:
                throw new InvalidEnumArgumentException("Invalid register");
        }
    }

    [Route("{id:int}")]
    public async Task<JobHeader> Get(int id)
    {
        var user = await GetApplicationUserAsync();
        if(id > 0)
        {
            var result = await Repository.GetSingleAsync<JobHeader>(j => j.ID == id);
            result.RoadSample = await Repository.Context.RoadSamples.GetNonTrackedSingleAsync(r => r.JobHeaderID == id);
            if(result.RoadSample != null)
            {
                result.RoadSample.Containers = await Repository.Context.JobContainers.GetNonTrackedListAsync(t => t.ContainerJobID == result.RoadSample.ContainerJobID);
            }
            return result;
        }
        return new JobHeader
        {
            BranchID = (short)user.BranchID,
            CreatedByID = (short?)user.UserID,
            JobCreateDate = DateTime.Now,
            JobStartDate = DateTime.Now,
            StatusID = 1,
            RoadSample = new RoadSample(true) // true generates containers list
        };
    }

    [HttpPost]
    [Route("")]
    public async Task<JobHeader> CreateJob(JobHeader jobHeader)
    {
        var user = await GetApplicationUserAsync();

        jobHeader.CreatedByID = (short?)user.UserID;
        jobHeader.BranchID = (short)user.BranchID;
        jobHeader.JobCreateDate = DateTime.Now;
        jobHeader.StatusID = 1;

        var sampleTemplateID = await Repository.Context.Fn_SampleTemplateIDGet(
             jobHeader.CarrierID,
             jobHeader.OperationID,
             jobHeader.CustomerSpecID,
             jobHeader.BranchID,
             jobHeader.ProductID,
             jobHeader.TestSpecID)
             .SingleOrDefaultAsync();

        if(!sampleTemplateID.HasValue)
        {
            throw new Exception("No sample template was found - an email has been sent to QA.");
        }

        var transaction = Repository.Context.Database.BeginTransaction();

        try
        {
            jobHeader.JobNumber = "TMPNUMBER";
            jobHeader.SampleTemplateID = sampleTemplateID.Value;
            await Repository.AddAsync(jobHeader);

            var containerJob = new JobContainerJob(jobHeader);
            await Repository.AddAsync(containerJob);
            jobHeader.RoadSample.ContainerJobID = containerJob.ID;

            var containers = jobHeader.RoadSample.GetUsedContainers();
            foreach(var container in containers)
            {
                containers.ContainerJobID = containerJob.ID;
                containers.ProductID = jobHeader.ProductID;
                containers.UserID = user.UserID;
            }

            var jobData = new JobData(jobHeader);
            await Repository.AddAsync(jobData);
            jobHeader.RoadSample.DataID = jobData.ID;

            // TODO: FIX next line containers save - throws an exception: The entity type OrderedEnumerable`2 is not part of the model for the current context.
            await Repository.AddAsync(container);

            await Repository.Context.Pr_RoadSamplesCreate(jobHeader.ID, jobHeader.SampleTemplateID, jobHeader.JobNotes, user.UserID);

            jobHeader.JobNumber = (await Repository.Context.Pr_JobsCreateNumber(jobHeader.BranchID)).FirstOrDefault();
            await Repository.UpdateAsync(jobHeader);

            transaction.Commit();
            return jobHeader;
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }

Any assistance would be greatly appreciated.

mercredi 29 avril 2015

Web API return csv file

I need to get a csv file from web api controller. I can not get "Save As" dialog to show up. Only text output shows up on the page. I tried both, calling Export from jquery and also plain old html

Controller:

[System.Web.Http.HttpGet]
public HttpResponseMessage Export()
{
    StringBuilder sb = new StringBuilder();
    IEnumerable<CustomerDiscount> list = this.subscriberRepository.GetSubscribers();

    foreach (CustomerDiscount item in list)
    {
        sb.AppendFormat(
            "{0};{1};{2};",
            item.CustomerName,
            item.CustomerNumber,
            Environment.NewLine);
    }

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(sb.ToString());
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("text/csv");
    return result;
}

Where to Store sensitive data/information

I have a Two Factor Authentication system where I need to store the Auto generated Code and the requested time in some form storage for retrieving it later purpose. I need to know what is the best way to store these sensitive information.

I was planning to use Session to store those sensitive information. When I googled, In some places people are telling its not recommended to use session to store sensitive information. Can any body explain why so.

Any suggestion to this will be highly appreciated.

Thanks

Difference between Task.Run and QueueBackgroundWorkItem in Asp.Net

What exactly is the difference using

Task.Run(() => { 
     LongRunningMethod();
});

or

HostingEnvironment.QueueBackgroundWorkItem(clt => LongRunningMethod());

I tested on an Asp.Net MVC application in which I kept on writing a line to a text file for about 10 minutes inside an asynchronous task which is invoked using Task.Run or QBWI.

It goes fine both using Task and QBWI. My async method keeps on writing to that file without any issues till 10 minutes. No disturbance from IIS I observed regarding its recycling.

So what is special about QueueBackgroundWorkItem then?

Array becoming empty after receiving into controller with AJAX call

I have a class named as SOMEOBJECT contains a list of name Extras.

Am trying to pass a data via AJAX call into my controller. Within the data received by the MVC controller the array showing proper length but the entire data inside the array object is empty.

Is there any solution for this?

am passing object of class SOMEOBJECT via AJAX call is something like this: I took it via F12 DEV tools FORM DATA

chk1Checked:false
chk2Checked:true
chk3Checked:true
Extras[0][id]:COMP1
Extras[0][itemType]:DROPDOWN
Extras[0][itemId]:111
Extras[0][itemValue]:EVAL1
Extras[1][id]:COMP2
Extras[1][itemType]:DROPDOWN
Extras[1][itemId]:112
Extras[1][itemValue]:EVAL2

Am able to see 'Extras' variable inside my controller with length of 2 but the inside data is NULL.

mardi 28 avril 2015

Removing element using jquery

I am using jquery token input in my program and according to a select list change i need to pass extra parameter to the search function. I am able to do it by below code.

$("#service").on('change', '.act_type', function () {  
qq = $(this).val();
var id = $(this).attr('id').split('-');
$("#token-input-code-" + id[1]).detach();
$("#code-"+id[1]).tokenInput("../Preapproval/Searchactivitycode?queryParam=q" + "&type=" + qq,{
theme: 'facebook',
preventDuplicates: true,
searchingText: 'Searching...',
tokenLimit: 1,
hintText: 'Activity code',
 });

the rows are creating dynamically. I will detach the current textbox having the token input when a change in select list is done. Otherwise a new textbox will be created by keeping the old one. Now it is detaching the old one and create a new one with same id and tokeninput. Searching also doing successfully. But i am facing one issue.

The token input $("#token-input-code-" + id[1]) is coming under <ul><li></li></ul and this li and ul is not getting removed so a small line will appear in the row top each time i done a change in select list. How can i remove the ul and li. It does not have an id only a class and the same class is used for another ul element in the form also.

show username in url after user logs in asp.net mvc routes

Once user logs in and go to home page, it should add username by default.after login even user try to go mysite.com , it should redirect to mysite.com/username

ex:

mysite.com/home -> http://ift.tt/1OAfx5w

Remote validation doesn't work when property to validate is inside a modal Bootstrap

I'm using ASP.NET MVC3.
When an user create an account, I need the chosen nickname be unique, so I use the Remote DataAnnotation like this :

public class UserModel
{
    [Required]
    [Remote("CheckNickname", "Validation", ErrorMessage = "This nickname is already used")]
    public string Nickname { get; set; }

    // ...
}

I used it in a strongly-typed view, via @Html.TextBoxFor(m => m.Nickname) and it perfeclty works.


However, I created another model with the exact same property.

public class MyOtherModel
{
    // ...

    [Required]
    [Remote("CheckNickname", "Validation", ErrorMessage = "This nickname is already used")]
    public string Nickname { get; set; }
}

I used this MyOtherModel.Nickname on a strongly-typed view via :
@Html.TextBoxFor(m => m.MyOtherModel.Nickname) However, in this case only, the data passed to my CheckNickame() method is always null.

There are only two differences :

  • In the second case, the property I want to remotely validate is contained in another model (is it a problem ? I don't think so...)
  • In the second case, the property is displayed inside a modal bootstrap (is it a problem ?)

For information, this is what my CheckNickname() looks like :

public JsonResult CheckNickname(string nickname)
{
    UserDAL userDAL = new UserDAL();
    bool userIsAvailable = !userDAL.IsUserAlreadyInUse(nickname);

    return Json(userIsAvailable, JsonRequestBehavior.AllowGet);
}

As I wrote it before, in the second case only, the parameter nickname is always null whereas it works as expected in the first case.

Is anyone knows why ?
Any help is appreciated.

Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IEnumerable

   @(Html.Telerik().Grid((IEnumerable<Pats.Entities.ViewModels.RecruitmentModel>)(ViewData["data"]))
                       .Name("gdTaskDescription")

                       .Columns(columns =>
                       {

                           columns.Bound(o => o.name).Width(200).Title("Name");
                           columns.Bound(o => o.title).Width(200).Title("Title");
                           columns.Bound(o => o.race).Width(200).Title("Race");
                           columns.Bound(o => o.sex).Width(200).Title("Sex");
                       })
                         )

This is Telerik grid binding with view data.During run time i am getting exception

lundi 27 avril 2015

how to upload file and save it to local database using angularjs

_CreateNewEmployee:

<h2>CreateNewEmployee</h2>

<table class="table" style="width: 100%">
<tr>
    <td style="text-align: left; width: 20%;">
           <label class="labelsytle">
             First Name
        </label>           
    </td>
    <td style="text-align: left;">
        <input class="form-control" name="search" ng- model="Empdet.FirstName" placeholder="Enter First Name" style="border-radius: 5px;" />
    </td>
</tr>
<tr>
    <td style="text-align: left;">
        <label class="labelsytle">
            Last Name
        </label>            
    </td>
    <td style="text-align: left;">
        <input class="form-control" name="search" ng-model="Empdet.LastName"  placeholder="Enter Last Name" style="border-radius: 5px;" />
    </td>
</tr>
<tr>
    <td style="text-align: left;">
        <label class="labelsytle">
            Email
        </label>
    </td>
    <td style="text-align: left;">
        <input class="form-control" name="search" ng-model="Empdet.Email" placeholder="Enter Email" style="border-radius: 5px;" />
    </td>
</tr>
<tr>
    <td style="text-align: left;">
        <label class="labelsytle" for="file">
            PhotoFile
        </label>
    </td>
    <td style="text-align: left;">
        <form action="" method="post" enctype="multipart/form-data">
        <input class="form-control" name="file" type="file" ng-model="Empdet.PhotoFile" id="file" style="border-radius: 5px;"/>
        </form>    
    </td>
</tr>
<tr>
    <td style="text-align: left;">
           <label class="labelsytle">
            PhotoText
        </label>
    </td>
    <td style="text-align: left;">
        <input class="form-control" name="search" ng-model="Empdet.PhotoText" placeholder="Enter PhotoText" style="border-radius: 5px;" />
    </td>
</tr>
<tr>
    <td style="text-align: left;">
           <label class="labelsytle">
            Age
        </label>
    </td>
    <td style="text-align: left;">
        <input class="form-control" name="search" ng-model="Empdet.Age" placeholder="Enter Age" style="border-radius: 5px;" />
    </td>
</tr>

<tr style="display: block; text-align: center; width: 5%; margin: 0 auto;">
    <td style="text-align: left; width: 25px;" colspan="4">
        <button class="btn btn-primary" type="button" ng-click="SaveEmpdet(Empdet)" style="border-radius: 5px; font-family: Consolas;">SAVE</button></td>

    <td style="text-align: left; width: 25px;">
        <button class="btn btn-primary" type="button" ng-click="Cancel()" style="border-radius: 5px; font-family: Consolas;">CANCEL</button></td>
</tr>


</table>

controllers.js:

angular.module('MyEmployee.controllers', ['ngDialog', 'ui.bootstrap'])
.controller("EmployeeDetailController", function ($scope, EmployeeFactory,   ngDialog) {
$scope.Empdet = {}
$scope.Empdet.FirstName = '';
$scope.Empdet.LastName = '';
$scope.Empdet.Email = '';
$scope.Empdet.PhotoFile = '';
$scope.Empdet.PhotoText = '';
$scope.Empdet.Age = '';
$scope.Empdet.Id = 0;

$scope.EditEmployeeShow = true;
$scope.ShowDeletePopup = true;
$scope.ShowAlert = true;

$scope.SaveEmpdet = function (newEmpdet) {
    console.log('save clicked')
    EmployeeFactory.SaveNewEmployee(newEmpdet)
    $scope.Empdet={};
    $scope.ShowAlert = false;
    $scope.EditEmployeeShow = true;
    $scope.SelectEmployeeList();
};

$scope.closeAlert = function () {
    $scope.ShowAlert = true;
};

$scope.Cancel = function () {
    console.log('cancel clicked')
};

$scope.DeleteEmployee = function (Id) {
    console.log('Delete clicked')
    console.log(Id);
    EmployeeFactory.DeleteEmployee(Id);
    $scope.SelectEmployeeList();
};

$scope.init = function(){
    $scope.SelectEmployeeList();
}

$scope.SelectEmployeeList = function () {
    console.log('Select in controller')           
    EmployeeFactory.SelectEmployeeList().success(function (response) {
        console.log('response.IsSuccessful');
        console.log(response.Data);

        $scope.IsSuccessful = response.IsSuccessful;
        if ($scope.IsSuccessful) {
            $scope.EmpdetList = response.Data;
            console.log('$scope.EmpdetList');
            console.log($scope.EmpdetList);                  
            $scope.CanClearMessage = true;
        } else {
            $scope.SuccessMessage = '';
            $scope.ErrorMessage = response.ReasonForFailure;
            $scope.CanClearMessage = true;
        }

        //$scope.tableParams = new ngTableParams({
        //    page: 1, // show first page
        //    count: 10, // count per page            
        //    sorting: {
        //        //name: 'asc' // initial sorting
        //    },
        //    filter: {
        //        //name: 'asc' // initial sorting
        //    }

        //}, {
        //    total: $scope.GetLists.length, // length of data                  
        //    getData: function ($defer, params) {                                    
        //        var filteredData = params.filter() ? $filter('filter')($scope.GetLists, params.filter()) : $scope.GetLists;
        //        var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : $scope.GetLists;                          
        //        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        //    }
        //});


    });
}    
})

_EmpdetList:

<h2>EmpdetList</h2>

<table class="table table-bordered table-hover table-striped" ng-table="tableParams" show-filter="true">
<tr ng-repeat="Empdet in EmpdetList">                       
    <td data-title="'Id'" filter="{ 'Id': 'text' }" sortable="'Id'">{{Empdet.Id}}</td>
    <td data-title="'FirstName'" sortable="'FirstName'" filter="{ 'FirstName': 'text' }">{{Empdet.FirstName}}</td>
    <td data-title="'LastName'" sortable="'LastName'" filter="{ 'LastName': 'text' }" >{{Empdet.LastName}}</td>
    <td data-title="'Email'" sortable="'Email'" filter="{ 'Email': 'text' }">{{Empdet.Email}}</td>
    <td data-title="'PhotoFile'" sortable="'PhotoFile'" filter="{ 'PhotoFile': 'text' }"><img src="{{Empdet.PhotoFile}}"/></td>
    <td data-title="'PhotoText'" sortable="'PhotoText'" filter="{ 'PhotoText': 'text' }">{{Empdet.PhotoText}}</td>
    <td data-title="'Age'" sortable="'Age'" filter="{ 'Age': 'text' }">{{Empdet.Age}}</td>

    <td data-title="'Action'">
        <div data-toggle="modal" data-id="{{Empdet.Id}}" data-index="{{$index}}" data-name="{{Empdet.Id}}" ng-click="DeleteEmployee(Empdet.Id)" title='Click to delete the Account' class="open-confirm-delete fa fa-trash-o deleterow" style="height: 24px!important;">
        </div>
    </td>

</tr>
</table>

@*<div class="modal fade" collapse ="ShowDeletePopup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">&times;</button>
                                    <h4 class="modal-title"  id="myModalLabel">Confirm Delete</h4>
                                </div>
                                <div class="modal-body">
                                    <input type="hidden" name="name" id="name" value="" />
                                    <p>
                                        Do you want to Delete
                                        <label id="name1"></label>
                                        ?
                                    </p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>                                       
                                    <button type="button" id="deletebutton" class="btn btn-danger danger" ng-click="DeleteEmployee(selected.Id)" data-dismiss="modal">Delete</button>
                                </div>
                            </div>
                        </div>
                    </div>*@


@*<div  id="confirmModal" aria-hidden="true">
 <div class="modal-dialog" >
 <div class="modal-header">
        <h3 class="modal-title">Confirm Delete</h3>
    </div>
    <div class="modal-body">
        Are you sure to delete the Account {{ selected.Empdet.Id }}           
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" ng-click="DeleteEmployee()">Delete</button>
        <button class="btn btn-warning" data-dismiss="modal">Cancel</button>
    </div>
</div>
</div>*@

This is my project i m currently working in using Asp.Net MVC using angularjs. In th project i need to get a image file(mention above as "PhotoFile") and want to store it in database and should display it. I need ur help friends to code it in angularjs in above "_CreateNewEmployee" HTML file. Please help me to make it work and Thanks in advance.

Function only excuting with debugger after creation

I have a Visual Studio 2013 project, ASP MVC 4 to be more specific.

I am working on some dynamics multiple selects, the should be filled with the selected options when I chose a value on the parent select.

It only works when I apply a debugger line to the top of the function.

Here is fSFiddle http://ift.tt/1PPozbL

Here is the function with the issue

function SetSelectedValues(elem)
    {
        debugger;
        var combo = "#serial" + String(elem);
        $(combo + ' option').each(function () {
            var valor = $(this).attr('value');
            var existe = jQuery.inArray(valor, serialsy);
            console.log(existe);
            //console.log(serialsx);
            if (String(existe) == '-1') {
                console.log('Existe');
                $(combo + ' option[value="' + valor + '"]').prop("selected", true);
            }
        });
    }

And here is the behavior on a video ;) http://ift.tt/1IhjbMz

Any help would be appreciated, thanks

IOC failing on deployment to server

I get the following error on deployment to my server:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

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

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   AEP.TSV.Controllers.TSVController..ctor(UnitOfWork unitOfWork) in c:\Users\s253107\Desktop\TransmissionSiteVisit\DD-TSV-2-2-0 2015 Enhancements Project\AEP.TSV\AEP.TSV\Controllers\TSVController.cs:25
   AEP.TSV.Controllers.PagesController..ctor(UnitOfWork unitOfWork) in c:\Users\s253107\Desktop\TransmissionSiteVisit\DD-TSV-2-2-0 2015 Enhancements Project\AEP.TSV\AEP.TSV\Controllers\PagesController.cs:20
   DynamicInjectordc4444d535c84ff6b45b93d62fc85c28(Object[] ) +82
   Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
   Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
   Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +157
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4106469
   Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41

[InvalidOperationException: An error occurred when trying to create a controller of type 'AEP.TSV.Controllers.PagesController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +207
   System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +50
   System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +88
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

The controllers in question are as follows...

using System.Web.Mvc;
using System.Web.UI;
using AEP.TSV.Models;
using AEP.TSV.Attributes;
using AEP.TSV.DAL;
using System.Web.Security;
using AEP.TSV.ViewModels.Controllers.Pages;
using NLog;

namespace AEP.TSV.Controllers
{
    [TSVAuthorize]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class PagesController : TSVController
    {

        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        #region Constructors

        public PagesController(UnitOfWork unitOfWork) : base(unitOfWork) { }

        #endregion
        public PagesController(){ }
        #region Actions

        //
        // GET: /dashboard

        public ActionResult Dashboard()
        {

            User currentUser = unitOfWork.UserRepository.Get(User.UserId);
            _logger.Info(currentUser.UserName.ToString());
            if (currentUser != null)
            {
                return View(DashboardViewModel.MapToViewModel(currentUser, unitOfWork));
            }

            FormsAuthentication.SignOut();
            return RedirectToAction("LogOn", "Account");
        }

        //
        // GET: /help

        public ActionResult Help()
        {
            return View(new HelpViewModel { TagGroups = unitOfWork.TagGroupRepository.GetAll() });
        }

        #endregion
    }
}

And

using AEP.TSV.Providers;
using System.Web.Mvc;
using AEP.TSV.DAL;
using System;
using NLog;
using System.Linq;
using System.Management;

namespace AEP.TSV.Controllers
{
    public class TSVController : Controller
    {
        protected UnitOfWork unitOfWork;
        private TSVPrincipal userInfo;

        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();


        public TSVController() { }


        protected TSVController(UnitOfWork unitOfWork)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
            ManagementObjectCollection collection = searcher.Get();
            string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

            username = username.Substring(5, username.Length - 5);


            string ff = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            ff = ff.Substring(5, ff.Length - 5);

            this.unitOfWork = unitOfWork;
            ITSVMembershipProvider MembershipService = new TSVMembershipProvider(unitOfWork);
            Models.User user = MembershipService.CreateOrUpdateUser(username);
            //Models.User user = MembershipService.CreateOrUpdateUser(Environment.UserName);
            _logger.Trace(Environment.UserName + "  Renison Trace");
            TSVPrincipalSerializeModel serializedModel = new TSVPrincipalSerializeModel(user);

            TSVPrincipal principal = new TSVPrincipal(serializedModel);
            userInfo = principal;
        }

        protected new TSVPrincipal User
        {
            get { HttpContext.User = userInfo; return userInfo; }
        }

        /// <summary>
        /// Helper that renders a razor view as string. Primary purpose is to be passed as a message in JSON.
        /// </summary>
        /// <remarks>Code created by Stackoverflow community. Can be found here: http://ift.tt/1f8TTi0 </remarks>
        /// <param name="viewName"></param>
        /// <param name="model"></param>
        /// <returns>The string representation of the rendered razor view.</returns>
        protected string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

        protected override void Dispose(bool disposing)
        {
            unitOfWork.Dispose();
            base.Dispose(disposing);
        }
    }
}

I have added parameter-less constructors after going through some questions on SO, but I continue to get this error anyways. I suspect that the following code is causing this error,

protected TSVController(UnitOfWork unitOfWork)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
            ManagementObjectCollection collection = searcher.Get();
            string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

            username = username.Substring(5, username.Length - 5);


            string ff = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            ff = ff.Substring(5, ff.Length - 5);

            this.unitOfWork = unitOfWork;
            ITSVMembershipProvider MembershipService = new TSVMembershipProvider(unitOfWork);
            Models.User user = MembershipService.CreateOrUpdateUser(username);
            //Models.User user = MembershipService.CreateOrUpdateUser(Environment.UserName);
            _logger.Trace(Environment.UserName + "  Renison Trace");
            TSVPrincipalSerializeModel serializedModel = new TSVPrincipalSerializeModel(user);

            TSVPrincipal principal = new TSVPrincipal(serializedModel);
            userInfo = principal;
        }

any help in figuring out this issue is greatly appreciated. Thanks.

Route table issue in MVC 3/4/5 application [on hold]

Lets say we have two controller HomeController and DocumentController and there is a "Index" action method in HomeController and "Add" action method in DocumentController.

In register route(global.asax) there is a entry of home/index.

But when I try to access Document/Add It doesn't throw any page not found error. Ideally it should, as there is no entry for route "Document/Add" in register route in global asax.

How come this happens ?

Internet Explorer 9, tab spinning wheel stopped before page finishes loading

I am working on an ASP.net web application. The spinning wheel on the internet explorer tab disappears, before the webpage fully loads. The reason for using internet explorer, is because it is the primary web browser. Users may assume that the data they requested will not be returned by the browser, as the page loads around a minute later and the spinning wheel is not visible.

When i run an instance of the web application from the server and an instance of the web application from visual studios simultaneously, the spinning wheel functions correctly on one webpage and doesn't on the other.

The model item passed into the dictionary is of type, but this dictionary requires a model item of type

Issue: Line: 33

    The model item passed into the dictionary is of type 'Public.Web.Models.PaymentViewModel', but this dictionary requires a model item of type 'Public.Web.Models.BadCheckSearchViewModel'. 
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'Public.Web.Models.PaymentViewModel', but this dictionary requires a model item of type 'Public.Web.Models.BadCheckSearchViewModel'.

    Source Error: 


    Line 31:                    
    Line 32:                        Payment for
    Line 33:                        @Html.Partial("_BadCheckSubmittedForPayment", ((Public.Web.Models.BadCheckSearchViewModel)(Model.BadCheckSubmittedForPayment)))
    Line 34:                         
    Line 35:                        @Html.LabelFor(model => model.Payment.ServiceChargeDisplay, new { @class = "label-inline" })

Server: Windows Server 2003R2 32bit

Index.cshtml

@using BootstrapSupport
@model Public.Web.Models.PaymentViewModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_BootstrapLayout.basic.cshtml";
}
<style type="text/css">
    .form-condensed .control-group {
        margin-top: 0;
        margin-bottom: 5px;
    }
    .label-inline {
        display: inline;
    }
</style>
@Html.Partial("_ReturnToSearch")
@using (Html.BeginForm("SubmitPayment", "Payment", FormMethod.Post, new { @class = "form-horizontal form-condensed", id = "paymentform" }))
                {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
    <div class="container">

        <div class="row">
            <div class="span4">
                @*@using (Html.BeginForm("UpdatePayment", "Payment", FormMethod.Post, new { @class = "form-horizontal form-condensed", id = "partialpaymentform"  }))
                {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                *@<div class="well">
                    <fieldset>
                        <legend>Payment for</legend>
                        @Html.Partial("_BadCheckSubmittedForPayment", (Public.Web.Models.BadCheckSearchViewModel)Model.BadCheckSubmittedForPayment)

Controller:

public ActionResult Index()
        {
            var paymentViewModel = new PaymentViewModel();
            try
            {
                if (Session["SubmittedBadCheckForPayment"] != null)
                {
                    BadCheckSearchViewModel submittedForPayment = Session["SubmittedBadCheckForPayment"] as BadCheckSearchViewModel;
                    if (submittedForPayment != null)
                    {
                        var uri = System.Web.Configuration.WebConfigurationManager.AppSettings["BadCheckServiceUrl"];
                        _ctx = new Public.Web.BadChecks.CmsPublicEntities(new Uri(uri));

                        paymentViewModel.BadCheckSubmittedForPayment = submittedForPayment;
//.........
                    }
                }
            }
            catch (Exception ex)
            {
//....
            }

            return View(paymentViewModel);
        }

Model:

public class PaymentViewModel
{
    private BadCheckSearchViewModel _badCheckSubmittedForPayment;

    public BadCheckSearchViewModel BadCheckSubmittedForPayment
    {
        get
        {
            return _badCheckSubmittedForPayment;
        }
        set
        {
            _badCheckSubmittedForPayment = value;
        }
    }

}

  • I have seen other posts where they say to make the @model declaration IEnumerable/List. I do not think this applies because I am not expecting it to enumerate through a list or I don't think I am.
  • This works on various other machines. The ones I know off the top of my head are: Windows Server 2012, Windows 7.
  • MVC 3, ASP.net Web Pages, .Net 2 and .Net 4 Client/Extended is installed
  • Experience Level with MVC: Entry-Junior
  • By the time the error has occured, we have accessed the site, searched. When selecting an entry to access this view, it errors.
  • I would love to solve this problem by telling them to upgrade to Windows Server 2012, but I can't.

Error with custom model in View

I have made my custom model to use in my View, and when I try to use it I get the error

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

And I don't know how to resolve it.
Here's my relevant classes and controller

Custom View Model

namespace Prep2.Models
{
public class MyProjectViewModel
{
    public IEnumerable<Project> Project { get; set; }
    public IEnumerable<MyProjectCustomObject> Data { get; set; }
}
}

MyProjectCustomObject

namespace Prep2.Models
{
public class MyProjectCustomObject
{
    public int ProjectId { get; set; }
    public string ProjectCustomer { get; set; }
    public string ProjectName { get; set; }

    public IEnumerable<TechProfile> ProjectTechProfile { get; set; }

    public int MemberId { get; set; }
    public string MemberRole { get; set; }
    public short? MemberStart { get; set; }
    public short? MemberEnd { get; set; }
}
}

Controller

        var Projects = from a in db.Project
                      select a;

        var Data = from a in db.Member
                   where a.Person.PersonId.Equals(Id)
                   select new MyProjectCustomObject
                   {
                       ProjectId = a.Project.ProjectId,
                       ProjectCustomer = a.Project.Customer,
                       ProjectName = a.Project.Name,

                       ProjectTechProfile = a.Project.TechProfile.Select(x => new TechProfile()
                       {
                           TechProfileId = x.TechProfileId,
                           Name = x.Name,
                           Elements = x.Elements
                       }),

                       MemberId = a.MemberId,
                       MemberRole = a.Role,
                       MemberStart = a.Start,
                       MemberEnd = a.End
                   };

        var MyViewModel = new MyProjectViewModel();
        MyViewModel.Project = Projects;
        MyViewModel.Data = Data;

        //return ViewModel to View.
        return View(MyViewModel);

Custom class for query

I have the following query in my Controller

public ActionResult Index(int Id)
{
    var People = from a in db.Person
                 select a;

    var Data = from a in db.Member
               where a.Person.PersonId.Equals(Id)
               select new CustomObject
               {
                   ProjectId = a.Project.ProjectId,
                   ProjectName = a.Project.Name,
                   ProjectCustomer = a.Project.Customer,

                   ProjectTechProfile = a.Project.TechProfile.Select(x => new
                   {
                       x.TechId,
                       x.Name,
                       x.Elements
                   }),

                   MemberId = a.MemberId,
                   MemberRole = a.Role,
                   MemberStart = a.Start,
                   MemberEnd = a.End
               };

And I'm making a custom class for my Data query, but I don't know how to set the property of TechProfile

Right now I have this in my custom class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyProject.Models
{
public class CustomObject
{
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }
    public string ProjectCustomer { get; set; }

    public IEnumerable<TechProfile> ProjectTechProfile { get; set; }

    public int MemberId { get; set; }
    public string MemberRole { get; set; }
    public short? MemberStart { get; set; }
    public short? MemberEnd { get; set; }
}
}

But the part with

public IEnumerable<TekniskProfil> ProjectTechProfile { get; set; }

Doesn't work, so do I need to specify TechId, Name and Elements? If so, how?

HTTP 404. The resource you are looking for

Server Error in '/' Application.

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /login.aspx

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34237

Returning more than just one model to the View?

I am fairly new to MVC, and I've been reading a bit about ViewModels, but how do I go about sending two models to my View, where the queries are like so

    public ActionResult Index(int Id)
    {
        var People = from a in db.Person
                     select a;

        var Data = from a in db.Member
                   where a.Person.PersonId.Equals(Id)
                   select new
                   {
                       a.Project.ProjectId,
                       a.Project.Name,
                       a.Project.Customer,

                       a.Project.TechProfile.Select(x => new
                       {
                           x.TechId,
                           x.Name,
                           x.Elements
                       }),

                       a.MemberId,
                       a.Role,
                       a.Start,
                       a.End
                   };

        return View(People);
    }

I was using @model IQueryable<GeoCV.Models.Person> before so I could use a @foreach in my View but I don't know how to get my other query to the View so I can get data from it too.

dimanche 26 avril 2015

ICollection circular reference

I have a LINQ query like so

var Data = from a in db.Medlem
                   where a.Person.PersonId.Equals(BrukerCv.Person.PersonId)
                   select new
                   {
                       a.Prosjekt.ProsjektId,
                       a.Prosjekt.Navn,
                       a.Prosjekt.Kunde,
                       a.Prosjekt.TekniskProfil,
                       a.MedlemId,
                       a.Rolle,
                       a.Start,
                       a.Slutt
                   };

and I want to return it like a json, so I use this

return Json(Data, JsonRequestBehavior.AllowGet);

but the problem I encountered is that I get the error

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.CVVersjon_4F0DBDC27A40F2FDF90760ABFDE49CBE0B75F52902B1C5F1E466393543AC44E8'.

Which I suppose is because of the a.Prosjekt.TekniskProfil which is an ICollection

So how can I get the ICollection?

Like, I don't want all the values in the ICollection TekniskProfil, just certain values

samedi 25 avril 2015

.Submit() not working

I have a from skeleton like below

@using (Html.BeginForm("Preapprove", "Preapproval", FormMethod.Post, new { name = "form1", id = "form1", enctype = "multipart/form-data", @class = "form-horizontal" }))
{
  ......
<input name="submit" type="button" value="Submit" id="Sub" class="btn btn-success" style="margin-left:950px" />                     


 }

And in jquery im submitting this form on the click even of the button id Sub

$(document).ready(function () {
            $('#Sub').click(function (e) {
              var error_flag = 0;



                if (diag_row_count == 1) {
                    error_flag = 1;

                }

                else if (diag_row_count > 1) {

                    if (code == null || code.trim() == '') {
                        error_flag = 1;

                    }

                    else if (serv_row_count == 1) {
                        error_flag = 1;

                    }

                }


                if (error_flag != 1) {
                    alert("submitting");
                    $("#form1").submit();
                 }


            });

When all the validation passed the error_flag will be 0 and it is getting inside the if condition and giving me the alert "Submitting" but the form is not getting submitted.

Anything im missing on the code?

How to bind list of objects in ASP.NET MVC when one item in between is deleted

I have an issue while Binding model To A List in MVC. My page has a functionality to add and delete text-box dynamically. My page HTML will be

<form id="prdt">
    <div id="div_0"> <input type="text" name="products[0].Name" value="Coffee"/><button id="0" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_1"> <input type="text" name="products[1].Name" value="Tea" /><button id="1" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_2"> <input type="text" name="products[2].Name" value="Cola" /><button id="2" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_3"> <input type="text" name="products[3].Name" value="Pepsi" /><button id="3" onclick="return DeleteLocation(this.id)">Delete</button></div>
</form>

Below is the code to delete the textbox

<script type="text/javascript">
    function DeleteLocation(id) {           
       $("#div_" + id).remove();
    }
</script>

But when I delete "Cola" text-box and do an ajax post I am getting only Coffee and Tea in my list(Controller Action Post). i.e last one is omitted in the list

Similarly when I delete "Tea" text-box and do an ajax post I am getting Coffee only. i.e other three values are excluded in the list.

I think list is binding with on List index. Is there any way to get all values even if any item in between is deleted.

vendredi 24 avril 2015

dapper sets column as 0

I'm querying the DB2 and I want to set it up using Dapper through MVC3. After testing it, the ProNumber ends up being 0 no matter what the search is. I know the ProNumber shouldn't be 0.

    public FreightBill Find(string search)
    {
        int searchInt;
        string query = @"SELECT DISTINCT
                      PRO ProNumber, 
                      DES ItemDescription, 
                      STYL StyleNumber, 
                      PCS HandlingUnits,

                      ACK Acknowledgment,
                      BL BillofLading,
                      PO PurchaseOrderNumber
                 FROM PROTABLE 
             WHERE ";

        if (int.TryParse(search, out searchInt))
        {

        }
        else
        {
            query += String.Format(" PRO     = {0} OR ", searchInt);
        }

        query += String.Format(@"
                  DES    = '{0}' OR
                  STYL   = '{0}' OR
                  PO     = '{0}'

                  FETCH FIRST 1 ROWS ONLY", search);

        return this._db.Query<FreightBill>(query).SingleOrDefault();



    [DisplayName("Pro Number")]
    [Editable(false)]
    public int ProNumber { get; set; }

    [DisplayName("Item Description")]
    [Editable(false)]
    public string ItemDescription { get; set; }

    [DisplayName("Style Number")]
    [Editable(false)]
    public string StyleNumber { get; set; }

    [DisplayName("Pieces")]
    [Editable(false)]
    public int HandlingUnits { get; set; }

    [Editable(false)]
    public string Acknowledgment { get; set; }

    [Editable(false)]
    public string BillOfLading { get; set; }

    [Editable(false)]
    public string PurchaseOrder { get; set; }
}

I know I should be using parameters, but when I tried it, the query timed out. I'm not sure why.

Nullable Datetime object custom data annotation validation

I have a view model with 3 DateTime properties. StartDate EndDate ValueDate

All the date properties are optional except the EndDate. I have added a validation Attribute to the properties. My issue is when I call the IsValid(object value) method, the value parameter comes back with a default even if there is no data passed to the object.

How do I Validate a nullable DateTime object if Im expecting it's value to be null and the property is defaulting to a system default date.

public class TestClass
{
[CusomValidator]
public DateTime? StartDate {get;set;}
[CusomValidator]
public DateTime? EndDate {get;set;}
[CusomValidator]
public DateTime? ValueDate {get;set;}
}

public class CusomValidator: ValidationAttribute
{
public bool IsValida(object value)
{
 //At this point value has the default system DateTime
 // When a post if made, the properties which are suppose to be null are null and that is what I want
}
}

What I am trying to achieve he is: There is a minim mum date that is selectable, The minimum date is stored in the application settings (Properties.Settings). When ever the StartDate is set, then I dont want to apply the minimum date validation on the ValueDate, vice versa. The user interface allows on one of the two(StartDate and ValueDate) to be selected. If one is slecetd then the other is set to null and on the web (DataAnnotation) I only want to validate a DateTime? property that has a value.

Counteract a bootstrap / select2 rendering delay?

I'm using bootstrap on a site, and using the following code on load to turn my select boxes into select2 dropdowns

$("select").select2();

However when any page with a select dropdown loads, there's a brief delay where the original can be seen before the select2 replacement is drawn in. This is quite jarring as elements of the forms on my pages move around.

Is there a way to generate the select2 HTML in my backend (ASP MVC3) and write it out to the page in such a way that the select2 plugin will still hook up all the behaviours correctly?

Passing values in a view from controller after getting those values from same view

I am new to MVC

I want to pickup "fromDate" and "ToDate" from a view. In the same view I need three dropdownlist which are empty and hidden.

After clicking on submit button , those dropdownlist should be visible and filled with data based on dates picked.

But I am getting 'null reference' error on view page .

Please help ?

My View Page is

<h2>View Data in Database</h2>
<table><tr><td>
@using(Html.BeginForm("ViewPage1","Home"))
{
   <table><tr><td>From Date:</td>
              <td>@html.TextBoxFor(m=>m.FromDate,"{0:dd/MM/yyyy}")</td>
          </tr>
          <tr><td>To Date:</td>
              <td>@html.TextBoxFor(m=>m.ToDate,"{0:dd/MM/yyyy}")</td>
          </tr>
          <tr><td><input type="submit" Value="Show"></td>
              <td><input type="submit" Value="Show"></td>
          </tr>
   </table>
   <div id="ShowDropBoxes">
   <table>
        <tr><td>@Html.CheckBox("Production Order:", new{id="ck1"})</td>
            <td>@Html.DropDownlistFor(m=>m.ProdNo, Model.ProdOrdList, "Select Production Order")</td>
        </tr>
         <tr><td>@Html.CheckBox("Part Number:", new{id="ck2"})</td>
            <td>@Html.DropDownlistFor(m=>m.PartNo, Model.PartNoList, "Select Part Number")</td>
        </tr>
         <tr><td>@Html.CheckBox("Status:", new{id="ck3"})</td>
            <td>@Html.DropDownlistFor(m=>m.StatusTxt, Model.StatusList, "Select Status")</td>
        </tr>
   </table>
   </div>

My Model is

  public class HomeModel
  {
      public DateTime FromDate {get; set; }
      public DateTime ToDate {get; set; }
      public string ProdNo {get; set; }
      public string PartNo {get; set; }
      public int status {get; set; }
      public System.Web.Mvc.SelectList ProdNoList {get; set; }
      public System.Web.Mvc.SelectList PartNoList {get; set; }
      public System.Web.Mvc.SelectList StatusList {get; set; }
  }

Controller Is:-

  public class HomeController: Controller
  {
       Repository List_in_Repository = new Repository();

       public ActionResult ViewPage1()
       {
           return View();
       }
       [HttpPost]
       public ActionResult ViewPage(HomeModel model)
       {
             string fromdate = model.FromDate.Tostring("yyyyMMdd");
             string todate = model.ToDate.Tostring("yyyyMMdd");
             model.ProdNoList = new SelectList(List_in_Repository.GetProductionOrders(fromdate,todate));
             model.PartNoList= new SelectList(List_in_Repository.GetPartNumbers(fromdate,todate));
             model.StatusList = new SelectList(List_in_Repository.GetStatus(fromdate,todate));
       }
   }

how to load set of HTML files in ASP.NET MVC view

I have some training modules which I want to load from my MVC site (SSL). I am trying run them as following but it does not load their css and images. Also I am not sure if it will let me to move to other html pages with in the same module by clicking the links on index.html.

Can anyone please suggest me a batter way of doing?

public ActionResult DisplayModule(string path)
{
    return new DisplayModule(path, "text/html");
}

Thanks in Advance.

jeudi 23 avril 2015

Unity Share Single Instance Between Multiple Objects

While working on some test application , I faced a scenario where I want to share one instance of a class among other instances through Unity .

I have a interface called ICommon and this is been implemented in Common class . I have two other interfaces IInterface1 and IInterface 2 and the have been implemented in Class1 and CLass2 . But Class1 and Class2 has a dependency on ICommon and this dependency gets resolved through Unity . But my problem is they are not sharing the same instance rather they it's creating multiple instances of ICOmmon . So I am looking for something through which Unity will share the same object if it's created already or will create a new one .

public interface ICommon { void Method1(); }

public class Common : ICommon
{
    public void Method1()
    {
        return;
    }
}


public interface IInterface1
{
    void Function1();
}

public class Class1 : IInterface1
{
    private readonly ICommon _common;
    public Class1(ICommon common)
    {
        _common = common;
    }
    public void Function1()
    {
        return;
    }
}

public interface IInterface2
{
    void Function1();
}

public class Class2 : IInterface2
{
    private readonly ICommon _common;
    public Class2(ICommon common)
    {
        _common = common;
    }
    public void Function1()
    {
        return;
    }
}

public static void RegisterComponents()
{
    var container = new UnityContainer();
    container.RegisterType<IInterface1, Class1>();
    container.RegisterType<IInterface2, Class2>();
    container.RegisterType<ICommon, Common>();

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

public class Test
{
    private IInterface1 _interface1;
     private IInterface1 _interface2;
    public Test(IInterface1 interface1, IInterface2 interface2)
    {
        _interface1 = interface1;
        _interface2 = interface2;
    }
}

So I want one instance to be created for ICommon and would be shared between Class1 and Class2 .

Editor Templates render multiple times (using Jquery)

public class PersonViewModel
{
 Public string PersonName{get; set;}
 Public string NumberOfCars{get;set;} // DropDown
}
Public Class CarViewModel
{
 Public string CareMake{get; set;}
Public string  Year{get; set;}
}

On a Page I have to initially display PersonViewModel related controls. Based on Number Of Cars selected( 2 or 3) I should be showing Input fields for CarViewModel (Which is an Editor Template)

Problem: I have written Editor Template for CarViewModel. Not sure how to call it dynamically based on drop down selected (i.e., NumberOfCars selected by person).

PS

  • I can Create Partial views and render multiple times dynamically based on dropdown selection. But not sure How to model bind child(CarViewModel) to Parent ViewModel which is PersonViewModel in case.
  • I haven't written all code for easy understanding of problem.

MVC3 assemblies dropped on system reboot

Every time I reboot my computer and reopen VS2012 all of the assemblies related to MVC3 claim to be missing. The only way to fix this is to uninstall then reinstall the ASP.Net MVC3 package.

I tried running the repair function on the VS2012 installer, and that did not work. Should a full reinstall fix the problem? What could be causing it in the first place?

Binding Image in ASP.NET MVC4 from a byte array

I am binding an image from a byte array in MVC4 view , The byte array is returned from a WEB API which I need to bind it to a view .

Below is the code

string str="JVBERi0xLjUNJeLjz9MNCjQgMCBvYmoNPDwvRSA0NDc1L0ggWyA3NjMgMTI1IF0vTCA1MTczL0xpbmVhcml6ZWQgMS9OIDEvTyA2L1QgNDcwMj4+DWVuZG9iag0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA0xNCAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbNCAxMV0vSW5mbyAzIDAgUi9MZW5ndGggNTQvUHJldiA0NzAzL1Jvb3QgNSAwIFIvU2l6ZSAxNS9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiZBBgYGJg2gAkGHeAiLlAgiEHSPAUMTAxfhADcRkYmf4zffrPxCCQAuS+C2cAALmiCM4KZW5kc3RyZWFtDWVuZG9iag1zdGFydHhyZWYNIDANJSVFT0YNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0N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ZpbHRlciAvRmxhdGVEZWNvZGUvRmlyc3QgOS9MZW5ndGggMTM0L04gMi9UeXBlIC9PYmpTdG0+Pg1zdHJlYW0KeJwzUjBQMFYwNlewsdF3zi/NK1Ew1PfOTClWiDYDygTF6odUFqQq6AckpqcW29mBFBWlJpZk5ue5JJakKmi4WBkZGJoamBgaGxkYmRqYRhkYqAORpr5vfgoBFQFF+SmlyalFChoBLm4hRfl5CkDaL7VERyHMTM/YwMjEKCZP084OAIrZKrEKZW5kc3RyZWFtDWVuZG9iag0xMyAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbMCA0XS9JbmZvIDMgMCBSL0xlbmd0aCAyNC9Sb290IDUgMCBSL1NpemUgNC9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiAAImRsFqIPG+jYEJyGMEABJTAg0KZW5kc3RyZWFtDWVuZG9iag10cmFpbGVyDTw8L1NpemUgNA0vSUQgWyhuXDM2NFxmXDIzNlwzMjVcMjYyfVwyNjRcMjcwXDM1MCpcMTc3XDAzN1wzNjdcMDA3XDMxNikgKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KV0+Pg1zdGFydHhyZWYNMTgyDSUlRU9GDQ==";

                   Byte[] image = GetBytes(str);

                    {
                        Model.ImageData = image;
                    }

 static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

in view Bind it as

 <img src="data:image;base64,@System.Convert.ToBase64String(Model.ImageData)" />

The image is not rendering , it is showing an image icon only in page .

Where it is going wrong .Please suggest .

Custom String Helper in C#

I created a helper method that takes a string and replaces all of the newlines with HTML line breaks. I currently have the method in a helper class that needs to be called statically.

How can I simply add my helper method to the builtin C# string class?

So this is what I would like to be able to do:

m.MailingAddress = m.MailingAddress.ReplaceNewlines("<br />");

This is what I am doing currently:

m.MailingAddress = Utility.ObjectExtensions.ReplaceNewlines(m.MailingAddress,"<br />");

Read/Write Session coupled with Asynchronous Action and Task Thread. How does the Controller behave then?

In an Asp.Net MVC application if an Asynchronous Controller's Session behavior is non-ReadOnly (means we can read and write to the Session), Our Controller's Action method is Async and within it we create a Task Thread that does some long running stuff, example:

public void UploadFilesAsync(IEnumerable<HttpPostedFileBase> assetFiles, 
                             string filesMetaInfo)
{
    var postedFiles = assetFiles;
    var fInfo = filesMetaInfo;

    AsyncManager.OutstandingOperations.Increment();

    Task.Factory.StartNew(
      () => ProcessUploadedFile(postedFiles, fInfo),
      CancellationToken.None, TaskCreationOptions.DenyChildAttach, 
      TaskScheduler.FromCurrentSynchronizationContext());
}

public ActionResult UploadFilesCompleted(object result)
{
   return Json(new
   {
      status = "OK"
   }, "text/plain");
}

private void ProcessUploadedFile(IEnumerable<HttpPostedFileBase> 
                     assetFiles, string filesInfo)
{
        // Do some long running stuff here like file processing.
        // ......................
        // ..................................

        AsyncManager.Parameters["result"] = "success"
        AsyncManager.OutstandingOperations.Decrement();
}

Two questions now:

  1. Then will this Controller Action method release this Controller for other Requests when once the inside created Task thread completes fully or will the Controller be available to other Requests right after when the Task Thread just starts executing inside UploadFilesAsync() method ?

  2. Also what will happen if I make this UploadFilesAsync() method behave in a synchronous manner by applying Synchronized attribute on it, example:

    [MethodImpl(MethodImplOptions.Synchronized)]

Facebook sharing shows wrong image in mvc3

Can anybody tell me why Facebook sharing shows wrong image??Below is my code

<html>
<head>
 <meta property="og:image" content="IMG_URL" />
    <meta property="og:description" content="desc" />
    <meta property="og:title" content="Title" />
</head>
<body>
 <div>
        <a href="http://ift.tt/1G9Egnb
URL&p[images]=IMG_URL
&p[title]=Title&p[summary]=summary">Share on Facebook</a>
    </div></body></html>  

mercredi 22 avril 2015

Not able to add breakpoint in HTML view (MVC3)

Recently I uninstalled and reinstalled VS2010 professional pack in my machine.

And after this, I was not able to add breakpoints in the view page and not able to debug the c# codes in my view page.

Please help!!

Not able to export russian or turkish characters to csv from asp.net mvc

I am exporting the data into csv from asp.net mvc controller using the File method like below. It works fine for english,french but not working for some other languages likes russian,turkish. Any thoughts or help will be much helpful.

var bytes = Encoding.Unicode.GetBytes(csv);
var finalData = new System.Text.UnicodeEncoding().GetPreamble()
                    .Concat(bytes).ToArray();
ActionResult result = this.File(finalData, "text/x-csv", filename);

How to send data from SignalR client to server in the Form Data?

I want to configure my SignalR connection to send data from client to server with every request. I currently use the querystring to send this data like that.

// Client
$.connection.hub.qs = "val=324";

and server-side:

// Server
var val = Context.QueryString["val"]

But as this data could be larger than what a querystring can deal with, I want to send it in the Form. I've found a function called ReadForm but I couldn't find any example for how to use it, or whether it's meant for that or not. I've also tried to pass state between client and hub, but I always get null at server-side.

I'm using SignalR version 2.1.2

Object doesn't support property or method 'colorbox'

I have an asp.net mvc page that allows a user to add Items to a list. The items are anchor elements that when click on, open up a pop box displaying detailed information about the item. Here is an example of an Item: Gettysburg College</a> -->

After adding an item to the dom model, the following call is made

$('a.SchoolDetails').colorbox({ overlayClose: false, iframe: false, overlayClose: true, width: 770, height: 530, close: "Close", onOpen: function () { $('#cboxLoadingGraphic').show(); }, onComplete: function () { $('#cboxLoadingGraphic').hide(); Initialize(); $('#cboxLoadedContent').css('overflow', 'hidden').css('height', '100%'); } });

The first item added to the page works as expected but subsequent calls fail with an Object doesn't support property or method 'colorbox' exception. The element does contain the cboxElement class attribute. But when the user clicks on the link, the colorbox height and width are not set according to the parameters passed into the $('a.SchoolDetails').colorbox() call. Has anyone encountered this problem?

Gettysburg College -->

mardi 21 avril 2015

NullReferenceException call the method of service from controller

Here is my controller

[Authorize]
public class ReportController : BaseController
{
    private IReportService  reportService;

    public ReportController(IReportService reportService)
    {
        this.reportService = reportService;
    }

    public ReportController()
    { 

    }

    [HttpPost]
    public String Test(TestParamViewModel model)
    {
        var result = reportService.GetTestReport(model.StartTime, model.EndTime);
        ........
    }

}

Here is my Interface

public interface IReportService
{
    IEnumerable<SvcReport> GetTestReport(DateTime startTime, DateTime endTime);
}

When I click generate button, I would like to call the method of service from controller but I got the following error. "NullReferenceException was unhandled by user code. Object reference not set to an instance of an object."

Thanks

How to fetch current domain or url with jquery in mvc website

Hi i need to get current domain name or url with jquery in my MVC website.

Here is my code:

 <script>
 // var ROOT = 'http://192.168.1.100/';
  var ROOT = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
  $(document).ready(function () {
  $('.button-search').click(function () {
window.location =ROOT + "Products/Index?DepartmentId=" +  $.trim($('#filter_name').val());                               
    });
});

My website url liks like this way:

 http://ift.tt/1JQVVUD

          OR
http://ift.tt/1EpRrFE

I want to fetch http://192.168.1.100/ or www.abc.com/ with the help of jquery in my above code.

Please suggest.

Angular 1.3.15 front end on asp.net MVC 3 backend

We have an existing asp.net mvc 3 applicaiton. We want to reskin it with angular 1.3.15.

I'm looking for a tutorial or example that takes a asp.net mvc 3 application and using the correct 1.3.15 syntax shows how to set up all the angular front end talking to the .Net backend.

I can find lots of angular 1.2 examples, but they dont' work under .1.3.15.. routing is different, 1.2 style submit doest't work.. I'm wasintg all my time trying to find out esoteric differenteces betwee 1.2 and 1.3, when I'm trying to learn the very basics of an angular mini spa app on top of ask.net mvc with best practices.

Can you pleae point me towards tutoprial or code samples that teach best practices with 1.3.5 syntax on the front end, binding routing etc..to asp.net mvc on the back end (3,4 or 5)

There are so many 1.2 examples and tutorials, that I can't find the wheat for the chaff...

Unity Throws Exception While Instantiating Inherited Objects

I am getting exception when unity trying to resolve my object . Below is my test code and I am getting this exception .

The current type, XXXXXXX, is an interface and cannot be constructed. Are you missing a type mapping?

namespace TrainMe.Data
{
    public interface ITestUnity
    {
        void Hello();
    }

    public class TestUnity : ITestUnity
    {
        public void Hello()
        {
        }
    }

    public interface IDerieve
    {

    }

    public abstract class Base
    {
        private ITestUnity _testUnity;

        protected Base(ITestUnity testUnity)
        {
            _testUnity = testUnity;
        }
        public string HelloWorld()
        {
            return "Hello World";
        }
    }

    public class Derieve : Base, IDerieve
    {
        public Derieve(ITestUnity testUnity)
            : base(testUnity)
        {
        }
    }

}

public class TestFactory : UnityServiceHostFactory
    {
        protected override void ConfigureContainer(IUnityContainer container)
        {
            container.RegisterType<IDerieve, Derieve>();

        }
    }

in .CS file

private readonly IDerieve _testUnity;
public ActionService(IDerieve test)
        {
            _testUnity = test;
        }

I am not sure what wrong I am doing here . This is a WCF project and I am using the library described here in codeplex .

Login to different active directories programaticly in c#

The company that I work for has two active directories (ad1.com, ad2.com) because it has two different stores that had nothing to do with each other and plenty of users but now the managers of both stores need a page in common. So I need to create a login where the users could access using just their Active Directory username and password.

In the login page there should be a list to choose the active directory and after that the user Paul(paul@ad1.com) and the user Paul(paul@ad2.com) with their respective password should be able to access to the page.

I have the code needed for the logIn page for one AD and works great but I don't know if it's possible to make the page available for two ADs. Do I need some extra configuration on the server?

I google this but didn't find anything related.

How to get the value of dynamically created textbox on HttpPost

I am creating Textbox control Dynamically as following, but on HttpPost it is not returning anything back. I am expecting the value of textbox to be accessible in Controller on HttpPost. Can anyone please suggest me how I can achieve this. Thanks

Models

public class MyViewModel
{
    public ControlViewModel[] Controls { get; set; }
}

public abstract class ControlViewModel
{
    public abstract string Type { get; }
    public bool Visible { get; set; }
    public string Label { get; set; }
    public string Name { get; set; }
}

public class TextBoxViewModel : ControlViewModel
{
    public override string Type
    {
        get { return "textbox"; }
    }
    public string Value { get; set; }
}

Controller

public ActionResult Index(Guid? id)
{
    return Results(id);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // Logic here
}

View

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Site.master"
 Inherits="System.Web.Mvc.ViewPage<MySite.Model.ViewModels.MyViewModel>" %>

<div>
    <% using (Html.BeginForm("Index", "MyController", FormMethod.Post, null))
    { %>
        <% for (int i = 0; i < Model.Controls.Length; i++)
           { %>
               <%Html.RenderPartial("TextboxControl", (TextBoxViewModel)Model.Controls[i]); %>             
        <% } %>
        <input type="submit" value="Submit" class="btn btn-primary"/>       
    <% } %>
   </div>

UserControl

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MySite.Model.ViewModels.TextBoxViewModel>" %>
<div>
     <%
           var controlType = Model.Type;
           var controlName = Model.Name;               
     %>
     <%= Html.TextBoxFor(x => x.Value, new { id = controlName, type = controlType, @class = "input-medium" })%>
</div>

How i send parameter from view to controller

I need to pass one parament to the post action in view. I calculate sum int parameter and i want send him to view beside the model object. I have tried to put it on the object but is null in the view.

@{
Layout = "~/Views/Shared/Layout.cshtml";

List<Product> productsList = ViewBag.ProductsList;
int sumAllPayment = productsList.Sum(s => Convert.ToInt32(s.Price));

Model.Details = new DetailsForPay()
{
    SumAllPrice = sumAllPayment
};
}

lundi 20 avril 2015

jquery datatable with ajax of json datasource

I am trying to load data from Entity Framework of ASP.NET MVC using a jquery data table with AJAX. Somehow the data isn't showing up in the table. Need your help in understanding where i am going wrong.

when i execute the json in the browser it returns the following string

[{"Region1":"South2","RegionId":1},
{"Region1":"Ahmedabad","RegionId":2},
{"Region1":"Bangalore","RegionId":3},
{"Region1":"Bhubaneswar","RegionId":4},
{"Region1":"Bilshpur","RegionId":5}]

the code for json is

public class RegionJSONController : ApiController
{
    static azure_sociodataEntities1 ctx = new azure_sociodataEntities1();

    // GET: api/RegionJSON
    public dynamic Get()
    {
            return ctx.Regions.Include("Tags").Select(i => new { i.Region1, i.RegionId }).Take(5);
    } }

the html page is

            <table id="regionsdt" class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>Region ID</th>
                            <th>Region</th>
                        </tr>

                    </thead>
                    <tbody></tbody>
                </table>

<<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.6/css/jquery.dataTables.css">

<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.10.2.min.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.6/js/jquery.dataTables.js"></script>


    <script>
    function InitOverviewDataTable() {
        oOverviewTable = $('#regionsdt').dataTable(
        {
            "bPaginate": false,
            "bJQueryUI": true,  // ThemeRoller-stöd
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": true,
            "bAutoWidth": true,
            "bProcessing": false,
            "iDisplayLength": 10,
            "sAjaxSource": 'http://localhost:44379/api/RegionJSON'
        });
    }

    function RefreshTable(tableId, urlData) {
        $.getJSON(urlData, null, function (json) {
            table = $(tableId).dataTable();
            oSettings = table.fnSettings();

            table.fnClearTable(this);

            for (var i = 0; i < json.aaData.length; i++) {
                table.oApi._fnAddData(oSettings, json.aaData[i]);
            }

            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
            table.fnDraw();
        });
    }

    function AutoReload() {
        RefreshTable('#regionsdt', 'http://localhost:44379/api/RegionJSON');

        setTimeout(function () { AutoReload(); }, 30000);
    }

    $(document).ready(function () {
        InitOverviewDataTable();
        setTimeout(function () { AutoReload(); }, 30000);
    });


</script>

Issue with @Url.Action to generate Absolute Url in MVC website

Hi i am trying to create absolute URL with @url.action but getting issues yet.

Here is the code i am using:

  • Home
  • Contact
  • Both Home and Contact are in same View.

So here is the error description: When I run the website it shows this url and open website perfectly. Now if I click on "Contact" link it shows correct URL:

http://localhost:5423/Home/Contact After that I am clicking on "Home" Link it gives me wrong URL:

http://localhost:5423/Home/Home/Index Correct Url should be this:

http://localhost:5423/Home/Index I don't know why its retaining "Home" in URL.

This is what I wrote in Global.asax.vb

Public Class MvcApplication
Inherits System.Web.HttpApplication

Sub Application_Start()
    AreaRegistration.RegisterAllAreas()

    WebApiConfig.Register(GlobalConfiguration.Configuration)
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    AuthConfig.RegisterAuth()
End Sub
End Class

Here is the code for RouteConfig:

 Public Class RouteConfig
 Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
 routes.MapRoute( _
 name:="Default", _
 url:="{controller}/{action}/{id}", _
 defaults:=New With {.controller = "Home", .action = "Index", .id =   UrlParameter.Optional} _
)
End Sub
End Class

MVC3 Loading controls from database

I am working on a Portal written in MVC3. I have a new requirement to create Questionnaires. Each question have question type (e.g. Dropdown, textbox etc.). Which will be mentioned in Database. Table Structure is as following:

Question:

  • QuestionId
  • Type
  • Text
  • Options

Answer:

  • AnswerId
  • QuestionId (Ref)
  • Answer

Questionnaire:

  • QuestionnaireId
  • QuestionId (Ref)
  • AnswerId (Ref)

I want to display questions based on their types and store their answers in Answer table. I can display controls by writing some dynamic code but struggling, how to store data back on submit.

Any suggestions please.

System.Web.Mvc.Html.DisplayExtensions vs System.Web.WebPages

I am working on a mvc4 project armed with the knowledge of mvc3. On my razor view page, I have some html element such as: @Html.ActionLink("Edit", "EditClubDate", new { id=item.ID }). But I also found that in the namespace of System.Web.Mvc.Html.DisplayExtensions there is also a method call ActionLink. Does anyone know the difference?

Morover, I am getting errors in my error list on VS2012 that is written as System.Web.WebPages.HTml.HtmlHelper dose not contain a definition for 'ActionLink'. I have tried to modify my web.config file in both views folder and the top level folder.

Error:Microsoft odbc driver manager data source name not found and no default driver specified

Created one VB ActiveX Dll and register that dll in local system.

Added reference that dll into my MVC project.

And called into controller like

using VBProject;

Called that function inside my action like

    [HttpGet]
    public ActionResult TestIndex(int id)
    {
        VBProject.MyClass myCls = new VBProject.MyClass();
        var reslt = myCls.MyFunction(id, retId);
        ViewBag.myId = retId;
        return View();
    }

When executing the Myfunction I am getting error,

Microsoft odbc driver manager data source name not found and no default driver specified

Not able to produce Absolute url with @Url.Action in MVC

I have MVC website where i am trying to make absolute URL with url.action but not succeed yet.

Here is code i am using:

 <li><a href="@Url.Action("Index", "Home")">Home</a></li>
 <li><a href="@Url.Action("Contact","Home")">Contact</a></li>

Both Home and Contact are in same View.

So here is the error description:When i run website it shows this url and open website perfectly,now if i click on "Contact" link it shows correct URL:

 http://localhost:5423/Home/Contact

After that i am clicking on "Home" Link it gives me wrong URL:

http://localhost:5423/Home/Home/Index

Correct Url should be this:

http://localhost:5423/Home/Index

I dont know why its retaining "Home" in URL.

This is only the problem i am facing.Please give your views and suggestions.

Thanks

Stop Scrolling of foundation JoyRide using javaScript

When joyride of foundation starts it does scrolling and I tried a lot to stop scrolling so I changed the scroll speed to zero using java script but not working

Code

$('#tourId').attr({
            'data-options': 'scroll_speed : 0'
});

dimanche 19 avril 2015

Getting issue to generate Absolute Url's in MVC

Hi I am trying to generate Absolute Url.I found a code for this:



<li><a href="@Url.Action("Index", "Home", null, Request.Url.Scheme)">Home</a></li>
<li><a href="@Url.Action("Index","Products",null,Request.Url.Scheme)">Products</a></li>
<li> <a href="@Url.Action("Contact","Home",null,Request.Url.Scheme)">Contact</a></li>


According me this code will work,But if i am trying to pass "null" as third parameter then i gives error:


ERROR: 'null' is not declared. 'Null' constant is no longer supported; use 'System.DBNull' instead.


Can someone please suggest what i should need to change?


Thanks


Solved: mvc3 not accepting proper URL?

I've got a controller named "TafelController.cs" and a vieuw named "Berekenen.cshtml". (the names aren't made up by me.)


the url "http://localhost:5181/tafel/berekenen" somehow doesn't work, even when adding extensions to berekenen like ".cshtml". Decapitalizing the names of the controller and the vieuw also doesn't work. The thing is, I get the proper vieuw when I make the Index() method the following.



public ActionResult Index()
{

return View("berekenen");
}


which is weird, because that's what



http://localhost:portnum/tafel/berekenen


is. when setting that page as the startpage the URL differs a bit. Then it becomes



http://localhost:5181/Views/tafel/berekenen.cshtml


Does anyone have any idea what might be happening?


samedi 18 avril 2015

Trouble migrating OpenID to OAuth 2 for Google logins

I'm following Google's instructions to migrate my old OpenID login system to OAuth2, managed by DotNetOpenAuth. I'm choosing to stick with DotNetOpenAuth because I already have Facebook, Twitter, Microsoft logins, and more all relying on this.


I've decided to use the DotNetOpenAuth OAuth2 Client for Google NuGet package for the upgrade. And this new Google OAuth2-style login is working. However, I'm not getting an authorization code from the response as Google mentions in their documentation. And so I'm not able to upgrade my customers' old OpenIDs.


Here are the fields I am getting... enter image description here


With this response I believe I'm supposed to take the authorization code (which seems to be missing) and then query http://ift.tt/1yJFQ0y. Currently I'm using the accesstoken that is returned but I believe that's wrong.


Any idea what I might be missing? Here's the relevant code.


First I set things up in Global.asax.cs...



public static readonly GoogleOAuth2Client googleClient = new GoogleOAuth2Client(ConfigurationManager.AppSettings["googleClientID"], ConfigurationManager.AppSettings["googleClientSecret"], new string[] {"userinfo.email"});

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

OAuthWebSecurity.RegisterClient(googleClient, "Google", new Dictionary<string, object>() { { "access_type", "offline" }, { "openid.realm", "http://localhost:43383/user/google" }, { "response_type", "code" } });

...


Then here's my code in my controller...



[HttpPost]
public ActionResult Google()
{
MvcApplication.googleClient.RequestAuthentication(new HttpContextWrapper(System.Web.HttpContext.Current), googleRedirectUri);
return new RedirectResult("/user/google");
}

public ActionResult Google(string returnurl)
{
string userId = null;
string screenName = null;

GoogleOAuth2Client.RewriteRequest();

var authorization = MvcApplication.googleClient.VerifyAuthentication(new HttpContextWrapper(System.Web.HttpContext.Current), googleRedirectUri);
if (authorization != null)
{
userId = authorization.ProviderUserId;
screenName = HttpUtility.HtmlEncode(authorization.UserName);

var restClient = new RestClient("http://ift.tt/y43Ehm");
var restRequest = new RestRequest("oauth2/v3/token", Method.POST);
restRequest.AddParameter("code", authorization.ExtraData["accesstoken"]);
restRequest.AddParameter("client_id", ConfigurationManager.AppSettings["googleClientID"]);
restRequest.AddParameter("client_secret", ConfigurationManager.AppSettings["googleClientSecret"]);
restRequest.AddParameter("redirect_uri", googleRedirectUri.ToString());
restRequest.AddParameter("grant_type", "authorization_code");
var restResponse = restClient.Execute(restRequest);
var content = restResponse.Content;
}
...


restResponse.Content is coming back as ...



{
"error": "invalid_grant",
"error_description": "Incorrect token type."
}