The HTTP request was forbidden with client authentication scheme 'Basic' - wcf

I have this bug when i try to create a new user using a remote wcf service, other services work fine.
{"The HTTP request was forbidden with client authentication scheme 'Basic'."}.
My user controller
[AcceptVerbs("Post")]
public ActionResult Add(FormCollection collection)
{
_userRepository.Add(collection["Company"], collection["Email"], collection["ExternalIdentifier"]);
return RedirectToAction("LoggedInAsAdministrator", "Home");
}
my user repository
public void Add(string company, string email, string eid)
{
var user = new User { Company = company, Email = email, ExternalIdentifier = eid, AccountType = "pro", CountryCode = "NL", Language="EN" };
var createdUser = _proxy.CreateUser(user);
((IDisposable)_proxy).Dispose();
}
my user.cs:
[ServiceContract]
[XmlRoot("user")]
public class User
{
[XmlElement("company")]
public string Company { get; set; }
[XmlElement("country-code")]
public string CountryCode { get; set; }
[XmlElement("language")]
public string Language { get; set; }
[XmlElement("created-at")]
public DateTime? CreatedAt { get; set; }
[XmlElement("email")]
public string Email { get; set; }
[XmlElement("external-identifier")]
public string ExternalIdentifier { get; set; }
[XmlElement("id")]
public int? Id { get; set; }
[XmlElement("measurement-system")]
public string MeasurmentSystem { get; set; }
[XmlElement("profile")]
public string Profile { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("username")]
public string Username { get; set; }
[XmlElement("account-type")]
public string AccountType { get; set; }
[XmlElement("current-token")]
public string CurrentToken { get; set; }
}
my servermodel configuration
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="UsernameWithTransport">
<security mode="Transport">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<client>
<endpoint address="xxxxxxx" binding="webHttpBinding" bindingConfiguration="UsernameWithTransport" behaviorConfiguration="xxxxx" contract="xxxxx" name="xxxxx" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="xxxxxxxx">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Any Help PLEASE.

Since you have enabled basic authentication on service you need to send basic credentials (username/password) with request. Try adding following code before you call your service.
_proxy.ClientCredentials.UserName.UserName = "myuser";
_proxy.ClientCredentials.UserName.Password = "mypassword";

Related

XAML Binding - Cannot access array item

I'm trying to bind a property via MVVM pattern.
The payload is something like that:
{
"QualificationSummary": "For all positions individuals must have IT-related experience...",
"PositionRemuneration": [
{
"MinimumRange": "62639.0",
"MaximumRange": "137348.0",
"RateIntervalCode": "PA"
}
]
}
I Tried this, but did nor worked.
<Label>
<Label.Text>
<MultiBinding StringFormat="{}{0}{1}">
<Binding Path="PositionRemuneration[MinimumRange]"/>
<Binding Path="PositionRemuneration[MaximumRange]"/>
</MultiBinding>
</Label.Text>
</Label>
Any clues?
After spend some time understanding the problem, that's the solution.
The c# class:
public Positionlocation[] PositionLocation { get; set; }
public class Positionlocation
{
public string LocationName { get; set; }
public string CountryCode { get; set; }
public string CountrySubDivisionCode { get; set; }
public string CityName { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
}
and to access the property:
<Binding Path="MatchedObjectDescriptor.PositionLocation[0].LocationName"/>

Test WCF Service using postman

I developed my first WCF Service and I want to test using postman but I keep getting 404 not found error.
I tested it using WCFClient and it was working fine.
My Model
[DataContract]
public class chatbotModel
{
[DataMember]
public System.Guid id { get; set; }
[DataMember]
public string subject { get; set; }
[DataMember]
public Nullable<System.DateTime> date_started { get; set; }
}
My function:
public bool InsertChatBotData(chatbotModel model)
{
using (var chatBotContext = new regacrmEntities())
{
var id = Guid.NewGuid();
var NewchatBot = new a01_chatbot()
{
id = id,
date_entered = model.date_started,
date_modified = model.date_ended,
name = model.subject,
description = model.description
};
chatBotContext.a01_chatbot.Add(NewchatBot);
chatBotContext.SaveChanges();
return true;
}
}
[ServiceContract]
public interface ICrmService
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, UriTemplate = "InsertChatBotData")]
bool InsertChatBotData(chatbotModel model);
}
Postman request:
I added the header:
SOAPAction:http://tempuri.org/ICrmService/InsertChatBotData
This is because you visited the wrong URL, I suggest you enable the help document. Here is a demo:
<endpointBehaviors>
<behavior name="ESEndPointBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
You need to apply ESEndPointBehavior to the endpoint.
Then you can access the help document in your browser:
The help document includes the requested url, http verb and the requested format.

How can I add an array to a WCF data contract?

I am trying to use the following class in a Windows Communication Foundation project written in Visual Studio 2012:
[DataContract]
public class SimCoilData : SimInventoryItemData
{
[DataMember]
public UnitTemperature? RequiredCoolingHotspot { get; set; }
[DataMember]
public UnitTemperature? RequiredHeatingColdspot { get; set; }
[DataMember]
public UnitTemperature? HeatingHotspotLimit { get; set; }
[DataMember]
public TimeSpan? TimeToRequiredColdspot { get; set; }
[DataMember]
public TimeSpan? TimeToRequiredCoolingHotspot { get; set; }
[DataMember]
public TimeSpan? TimeToHeatingHotspotLimit { get; set; }
[DataMember]
public UnitLength Gauge { get; set; }
[DataMember]
public UnitLength Width { get; set; }
[DataMember]
public double[] Temperatures { get; set; }
public SimCoilData() : base()
{
}
}
Before the addition of the Temperatures array, data was being exchanged well between the server and the client. I added the Temperatures array, rebuilt the server application, and ran it. Then, in the client project, I updated the service reference and rebuilt the project. When I run the client, I get an error message that a meaningless reply was received, which could be caused by a few things, including a data contract mismatch. I have verified that the array is being populated on the server side. What is the correct procedure for adjusting my client application to accept the array?
The problem appeared to be that I had not reserved enough space in the client for the messages. I found that I could handle 250 doubles per object but not 300 doubles per object. A Google search for "WCF maximum message size" led me to the maxBufferSize and maxReceivedMessageSize parameters. With this configuration for my client, I was able to get all 1800 values in my arrays:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_ISimShopServiceLib"
openTimeout="00:01:00"
closeTimeout="00:00:05"
sendTimeout="00:01:00"
receiveTimeout="00:01:00"
maxBufferSize="5000000"
maxReceivedMessageSize="5000000">
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://localhost:1236/SimShopService" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_ISimShopServiceLib" contract="SimShopServiceReference.ISimShopServiceLib"
name="NetTcpBinding_ISimShopServiceLib">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

Connectionstring in MVC4

I am doing mvc practice and create a simple page for fetch data from database. During practice I notice one thing I create this class:
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
And in my web.config First I add this detail:
<connectionStrings>
<add name="con" connectionString="Server=XYZ;Database=mvc1;uid=sa;pwd=abcd;" providerName="System.Data.SqlClient"/>
</connectionStrings>
When I run this application it give me error that there are invalid columns name.
But after that I read about it on internet and I change the con to EmployeeContext the name of the class that I create and then its work fine. Like this:
<connectionStrings>
<add name="EmployeeContext" connectionString="Server=XYZ;Database=mvc1;uid=sa;pwd=abcd;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now I want to know for the now I create just one single simple class and I have to give the class name in the connection string. Then is there this mean that I have to create everytime new connection string for each class???
Thanks
For sample you have different class model :
namespace MvcMusicStore.Models
{
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
}
namespace MvcMusicStore.Models
{
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
}
using System.Collections.Generic;
namespace MvcMusicStore.Models
{
public partial class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; }
}
}
After that you have to adding App_data folder is a special directory in ASP.NET which already has the correct security access permissions for database access. From the Project menu, select Add ASP.NET Folder, then App_Data.
After you create a new connection strings:
<connectionStrings>
<add name="MusicStoreEntities"
connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
</configuration>
and then a class covering the different DbSet your Application :using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
}
}
If you want to create a new class you have just to put on the DbSet into the last class.
You can find all the details here : http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-4

Error on WCF Service when using IList or ICollection as a DataMember

I'm developing a sample system that use Entity Framework code first approach and MVC as user interface. Here I use WCF services to communicate with user interface and the system. When I use a List or a collection in my Employee entity It given following error. I'm sure that's due to the collection.
" An error occurred while receiving the HTTP response to http:/localhost/GreetingHost/EmployeeService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. "
Here are my entities and services that included in Greeting Project :
Employee.cs
[DataContract]
[KnownType(typeof(Greeting))]
public class Employee
{
[Key()]
[DataMember]
public string UserId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
[ForeignKey("EmployeeUserID")]
public virtual IList<Greeting> Greetings
{
get
{
if (this._greetings == null)
{
this._greetings = new List<Greeting>();
}
return _greetings;
}
set { _greetings = value; }
}
private IList<Greeting> _greetings;
}
Greeting.cs
[DataContract]
public class Greeting
{
[Key()]
[DataMember]
public int GreetingID { get; set; }
[DataMember]
public string Salutation { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public DayStatusWrapper DayStatusWrapper { get; set; }
[DataMember]
public string EmployeeUserID { get; set; }
[DataMember]
public virtual Employee Employee { get; set; }
}
GreetingDBContext.cs
public class GreetingDBContext :DbContext
{
public DbSet<Greeting> Greetings { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>().
HasMany(d => d.Greetings).
WithRequired(c => c.Employee).
HasForeignKey(c => c.EmployeeUserID).WillCascadeOnDelete();
modelBuilder.Entity<Employee>()
.HasKey(c => c.UserId);
modelBuilder.Entity<Greeting>()
.HasKey(c => c.GreetingID);
}
}
EmployeeServices.cs
public class EmployeeService
{
private GreetingDBContext db = new GreetingDBContext();
public void AddEmployee(string UserId, string Name, int Age)
{
Employee emp = new Employee();
emp.UserId = UserId;
emp.Name = Name;
emp.Age = Age;
db.Employees.Add(emp);
db.SaveChanges();
}
public Employee getEmployee(string UserId)
{
Employee selectedEmployee = null;
foreach (Employee item in db.Employees)
{
if (item.UserId == UserId)
{
selectedEmployee = item;
break;
}
}
return selectedEmployee;
}
}
I used WCF Service application to host the services. Here codes are from GreetingHost project.IEmployeeServices.cs
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
void AddEmployee(string UserId, string Name, int Age);
[OperationContract]
Employee getEmployee(string UserId);
}
EmployeeService.svc.cs
public class EmployeeService : IEmployeeService
{
Greeting.EmployeeService serviceImplementation = new Greeting.EmployeeService();
public void AddEmployee(string UserId, string Name, int Age)
{
serviceImplementation.AddEmployee(UserId,Name,Age);
}
public WcfGreating.Employee getEmployee(string UserId)
{
return serviceImplementation.getEmployee(UserId);
}
}
Service host successfully :
In my MVC application Used above service reference:
EmployeeServiceClient employeeService = new EmployeeServiceClient();
public ActionResult Profile(string id)
{
Employee emp = employeeService.getEmployee(id);
return View(emp);
}
When gathering employee from service , above mentioned CommunicationException was returned. Can anyone help me?
Thank You!
Edit :
Clients' Web.config
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="EmployeeService" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/GreetingHost/EmployeeService.svc"
binding="wsHttpBinding" bindingConfiguration="EmployeeService"
contract="EmployeeServiceReference.IEmployeeService" name="EmployeeService">
<identity>
<servicePrincipalName value="host/7TK3T3J.fareast.corp.microsoft.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Service's config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehaviors" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
</wsHttpBinding>
</bindings>
<services>
<service name="GreetingHost.EmployeeService" behaviorConfiguration="MyBehaviors">
<endpoint address="http://localhost/GreetingHost/EmployeeService.svc"
binding="wsHttpBinding" bindingConfiguration="wsHttpBindingWithTXFlow"
name="EmployeeService" contract="GreetingHost.IEmployeeService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
</system.serviceModel>
You may try this -
[IgnoreDataMember]
public virtual Employee Employee { get; set; }
Sorry for the late reply ;)
disable LazyLoading in DbContext.