Category Archives: Xml

Xml

[RESOLVED]IE8 and IE9 classifying JSON response-object as undefined

I wrote some code to manually invoke ajax instead of using jquery. It works fine in Firefox and IE10, but not in IE8 and 9.  The ‘POST’ works fine, actually, but the response-object arrives as ‘undefined’ in IE8 and IE9 (I’m using the ‘Mult-Browser’ simulator
program to run IE8 and 9).   I stepped through the code on the .Net side, in debug mode, to verify that the return Json(collection) is in fact a populated collection (has 34 items).

This is NOT a JSON.parse issue.  The issue is that JSON.parse can’t parse an undefined object. JSON.parse is working fine in IE10 and Firefox because the debugger isn’t showing ‘undefined’ for these browers.

Why  isn’t the .Net code ‘return json(collection)’ working for IE8 and 9?

Here’s my ajax code:

        function ajax(data, url, requestType, IsJSON, funcOnFailure, funcOnSuccess){
            var http = new XMLHttpRequest();
            http.open(requestType, url, true);
            if (requestType.toUpperCase() == "POST") {
                var postThisString = encodeDataAsPostString(data);
                http.setRequestHeader("Content-length", postThisString.length);
                if (IsJSON) {
                    http.setRequestHeader("Content-type", "application/json; charset=utf-8");
                }
                else http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            }
            http.setRequestHeader("Connection", "close");
            http.onreadystatechange = function () {//Call a function when the state changes.
                if (http.readyState != 4) return;
                if (http.status == 200) {
                    if (funcOnSuccess) funcOnSuccess(http.response);
                }
                else {
                   if (funcOnFailure) funcOnFailure("An error occurred: " + http.statusText);
                }
            }
            http.send(postThisString);
        }

The code above was  capturing httpReq.response  – which worked fine in Firefox and IE10 with JSON.parse. What seems to work for these browsers plus for IE8 as well is to  capture httpReq.responseText.

Until a moment ago I wasn’t even aware of this distinction.

[RESOLVED]Claims Authentication : Object reference not set to an instance of an object. MVC 5

Hello,

I’m trying to implement Claims Authentication in to my site, So far I have all the code and the config settings but when I run it I get

Object reference not set to an instance of an object.

on the last line

  public bool UserLoggedIn(UserProfile userProfile)
        {
            var userCredentials = new[] {
                    new Claim("UserId", Convert.ToString(userProfile.UserId)),
                    new Claim("UniqueId", Convert.ToString(userProfile.UniqueId)),
                    new Claim("Username", Convert.ToString(userProfile.Username)),
                    new Claim("Firstname", Convert.ToString(userProfile.Firstname)),
                    new Claim("Surname", Convert.ToString(userProfile.Surname)),
                    new Claim("Email", Convert.ToString(userProfile.EmailAddress))};

            var id = new ClaimsIdentity(userCredentials, "Forms");
            var cp = new ClaimsPrincipal(id);
            var token = new SessionSecurityToken(cp);
            var sam = FederatedAuthentication.SessionAuthenticationModule;

            sam.WriteSessionTokenToCookie(token); // Here is where the error is

            return true;
        }

now im not sure what I’m missing but heres the config settings

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit

http://go.microsoft.com/fwlink/?LinkId=301880

  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=SCOTTS-LAPTOPLOCALDB;Initial Catalog=TestDatabase; Trusted_Connection=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

  <system.webServer>
    <modules>
      <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </modules>
  </system.webServer>

  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false"></cookieHandler>
    </federationConfiguration>
  </system.identityModel.services>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Please help.

Thank you

Hi,

Harrison.Scott

var sam = FederatedAuthentication.SessionAuthenticationModule;

            sam.WriteSessionTokenToCookie(token); // Here is where the error is

It seems variable "sam" is an enum constant. Note that, you can’t add or call any methods on enum constant.

Check this site, may help u:

http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.web.sessionauthenticationmodule.writesessiontokentocookie.aspx

Hi Raju,

I have been through that site, and It didn’t help me unfortunately.

Any other suggestions?

Hi,

Checking documentation for "FederatedAuthentication", i found its not enum but static class.

check this site may help u:

http://msdn.microsoft.com/en-us/library/gg638729.aspx

[RESOLVED]getting null response from Java web service

Hi,

We are working on ASP.NET MVC application and are trying to consume a java web service but we are getting null response. We are not able to debug the JAVA web service.

We can access and get proper reponse from the same web service using SoapUI. Below are the error details of reponse (When tried with MVC application).

java.lang.IllegalArgumentException at PublishingService.convertData(Service.java:272): Expected rawData to be an instance of org.w3c.dom.Element but found – class java.lang.String

Can somebody please help on this ?

you should use a network tracer to get the soap body you are sending. the error means a node was string:

   <a>string value</a>

where an  element was expected:

   <a><b>…</b></a>

without the xsd and sample payloads when can not tell what you did wrong. you should fetch the xsd from the java web service, and compare your payload xml to find the error.

also what .net tool are you using to call the web service? did you add it as web reference? an issue you may run into is that java supports xsd’s with variants, but .net serialization does not. if the xsd has variants, you will need to write a custom soap
serializer.

You’re not sending a response in the correct format.  As we have no idea what the service expects and no idea what your code is sending it is impossible to give any specific advise.  If you can get the request working using SoapUI then use a tool like fiddler
to see what your .net code is sending and compare the two to see what the difference is.  From there you can try and amend your code so it sends the right thing.  A likely problem is that you are not correctly serializing your parameters.

[RESOLVED]Post Error, “Error converting value 'ID' to type” to

I changed a relationship between my Job and CustomerEmployee Class, I am trying to make a Post and I am getting a error. Using a break point I see that the Id’s are not making it back to the apiController. I have done some searching and I think it seems
it might be a Json issue, not sure how to correct it. I have 6 Id’s I am trying to Post but they are setup the same so I will show code for one of them

Error Message

$id: "1"
Message: "The request is invalid."
ModelState: {$id:2, newJob.CustomerEmployeePMId:[,…], newJob.CustomerEmployeeAdminId:[,…],…}
$id: "2"
newJob.CustomerEmployeeAccountantId: [,…]
0: "Error converting value 10 to type 'TexasExteriorSPA.Models.CustomerEmployee'. Path    'CustomerEmployeeAccountantId', line 1, position 150."
newJob.CustomerEmployeeAdminId: [,…]
newJob.CustomerEmployeePMId: [,…]
newJob.CustomerEmployeeSuperintendentId: [,…]

view

<select class="form-control" ng-options="customer.CustomerEmployeeId as customer.CustomerEmployeeFirstName + ' ' + customer.CustomerEmployeeLastName for customer in customerEmployeeArray | filter:{CustomerEmployeeRole : 'Accountant', CustomerId : currentItem.CustomerId}  " ng-model="currentItem.CustomerEmployeeAccountantId">
     <option value="" selected="selected">Customer Acct</option>
</select>

Angular Controller

//Post New Job
$scope.submitJob = function () {
    var data = {
        JobId: $scope.JobId,
        CustomerEmployeeAdminId: $scope.currentItem.CustomerEmployeeAdminId
    }
    $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
        console.log(data);
                 $scope.openNewJobModal.then(function (m) {
                   m.modal('hide');
                 });
    });
};

WebApiConfig

// Web API configuration and services
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
           name: "JobApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { controller = "apiJob", id = RouteParameter.Optional }
       );

apiController

 // POST api/<controller>
    public async Task<IHttpActionResult> PostnewJob([FromBody]JobViewModel newJob)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        using (var context = new ApplicationDbContext())
        {
            var job = new Job();

            Mapper.CreateMap<JobViewModel, Job>();
            Mapper.Map(newJob, job);

            context.Jobs.Add(job);

            await context.SaveChangesAsync();

            return CreatedAtRoute("JobApi", new { job.JobId }, job);
        }
    }

Job Class

 public class Job
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Int64 JobId { get; set; }
    public CustomerEmployee CustomerEmployeeAccountantId { get; set; }
}

CustomerEmployee Class

public class CustomerEmployee
{
    [Key]
    public int CustomerEmployeeId { get; set; }
    public string CustomerEmployeeFirstName { get; set; }
    public string CustomerEmployeeLastName { get; set; }
    public string CustomerEmployeeRole { get; set; }

    public Int64? CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

}

It has been suggested that I change the CustomerEmployee CustomerEmployeeAccountantId to int CustomerEmployeeAccountantId but I cannot do that as that is the relationship between those classes. I believe the other route to take is deserializing  JSON but
I am not sure how to do that here. 

First of all you the route you have added for jobapi is of no use. You can not have 2 routes with same
routeTemplate. As it will not make any difference. And try changing you ajax call like

$scope.submitJob = function () {
    var newJob =
{
JobId: $scope.JobId,
CustomerEmployeeAdminId: $scope.currentItem.CustomerEmployeeAdminId
}
var data = JSON.stringify(newJob);
    $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
        console.log(data);
                 $scope.openNewJobModal.then(function (m) {
                   m.modal('hide');
                 });
    });
};

[RESOLVED]how to receive a json response instead of xml

how can I get a json response instead of XML when calling a web API using mvc??

In WebApiconfig the Register method as below 

 public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "MobileApp/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //config.Formatters.Clear();
           config.Formatters.Add(new JsonMediaTypeFormatter());
           // config.Formatters.Add(new BsonMediaTypeFormatter());
        }

page source not found.should I change anything in the routes?

hi you can do one thing,

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

You have to add formatters

config.Formatters.Add(new JsonMediaTypeFormatter());

In Web API 2.2,  JSON is a default functionality i.e. a Web API method can receive JSON formatted data from client  as well as send JSON formatted data back to the client in its response.

"Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.".

So for JSON you don’t have to write any special code in C# since that is already there in Web API, but you need to make sure that you send an appropriate ajax request from jQuery.

For JSON response when using jQuery, you should use jQuery AJAX request as below with
dataType: "json". Note the attribute ‘dataType’ that tells the Web API about what is expected in Web API’s response. If you mention dataType as xml i.e. dataType:xml,  then Web API method will return data formatted as XML and not as JSON.

function CallAWebAPIMethod() {
            var data = {
                productId: 100,
                productDescription: "Product 123
            }
            $.ajax({
                url: 'api/MyWebApi',
                type: 'PUT',
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType:"json",
                success: function (data) {
                    alert(data);
                },
                error: function (x, y, z) {
                    alert(x + 'n' + y + 'n' + z);
                }
            });
        }

If you are calling Web API from .Net code and not from jQuery
then use C# code like below to get back JSON formatted data. Note the last line of code line which is telling the Web API to return JSON formatted data.

using (var client = new HttpClient())
{
    // New code:
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}

[RESOLVED]Best Way to dynamically add textboxes on radiobutton click in MVC for non-JS users

I have a requirement where i have to dynamically add textboxes based on the radiobutton click i.e if 1 click then add 1 textbox, 2 then 2 & so on upto 6.

With jquery we can easily achieve this. But for non-JS users what should we do.

Any idea what can be a generic solution like a custom HTMLHelper or Partial View.

Hi,

DreamBig

radiobutton click i.e if 1 click then add 1 textbox, 2 then 2 & so on upto 6.

clientside events should be handled only through JS.

DreamBig

Any idea what can be a generic solution like a custom HTMLHelper or Partial View.

above both are serverside logics, which are not useful here.

[RESOLVED]MVC and multi language website

Hi all, 

I am starting a new project and this time I would love to realize a multi language website. What is the best practice to realize a multi language website using MVC? 

Text stored in resource files? Text stored in a SQL Server database? for each language a new version of the website?

Main content of the website will be directly written by the user.

Thanks in advance for the help.

paolovigna

Main content of the website will be directly written by the user.

And it is MultiLanguage? Then you need a DB ( either relational, as SqlServer , either file based, as XML )

yes it is, I assume that people in Germany will write posts in German en people in Italy will write posts in Italian and so on. So my idea is to implement a website which, as default, will be loaded using the current language of the user (maybe base on IP
location of directly checking current local UI culture). Then of course, every user could manage to choose his/her own default language. 

read posts by afana:

afana.me/post/aspnet-mvc-internationalization-strings-localization-client-side.aspx

thanks a lot I have enough information 

[RESOLVED]Linq to XML help

My XML structure looks like this.

If I want to find out the value for Manufacturer which is Lenovo

how would i write the linq to xml?

i’ve got this now and it doesn’t work

XElement root = XElement.Load(file);
IEnumerable<XElement> address =
from el in root.Elements("item")
//where (string)el.Attribute("Property") == "Manufacturer"
select el;
foreach (XElement el in address)
{
MessageBox.Show(el.Value);
}

<item Property="Computer" >
<item Property="Manufacturer" Value="LENOVO" />
<item Property="Family" Value="Not Available" />
<item Property="Product Name" Value="10A9000TAU" />
<item Property="Model" Value="10A9000TAU" />
<item Property="Version" Value="ThinkCentre M93p" />
<item Property="Serial Number" Value="PB000400" />
<item Property="SMBIOS Asset Tag" Value="Not Available" />
<item Property="SKU Number" Value="Lenovo" />
<item Property="Chassis" Value="Not Available" />
<item Property="PC System Type" Value="Desktop" />
<item Property="Machine Type" Value="AT/AT COMPATIBLE" />
<item Property="Firmware Type" Value="BIOS" />
<item Property="Infrared (IR) Supported" Value="No" />
<item Property="UUID" Value="123456789" />
</item>

Hi

Following will return the "Lenovo". Try 

var items = (from i in doc.Descendants("item").Descendants("item")
                             where i.Attribute("Property").Value == "Manufacturer"
                             select i.Attribute("Value").Value
                             );

That’s great.

Due to the fact there’s several nodes with Manufacturer.

How do i filter to only Computer then Manufacturer?

From Chandrasekar’s answer, try to add an AND operator for Computer like:

var items = (from i in doc.Descendants("item").Descendants("item")
                             where i.Attribute("Property").Value == "Manufacturer" && i.Attribute("Property").Value == "Computer"
                             select i.Attribute("Value").Value
                             );

based on that code, it doesn’t pick up any data.

because Computer is a node before manufacturer.

They are on different descendants.

Not sure if code below will work but the idea is to get the descendants of Computer first. Then from the results, you get the Manufacturer.

var items1 = (from i in doc.Descendants("item")
              where i.Attribute("Property").Value == "Computer"
             );

var items2 = (from i in items1.Descendants("item")
              where i.Attribute("Property").Value == "Manufacturer"
              select i.Attribute("Value").Value
             );

 

Hi

Try the following. If you could post the entire xml data or some portion of the xml which has another items other than "Computer" it would be easy for us to answer the post.

var items = (from i in doc.Descendants("item").Descendants("item")
             where i.Attribute("Property").Value == "Manufacturer" && i.Parent.Attribute("Property").Value == "Computer"
                             select i.Attribute("Value").Value
                             );