Blog from Saravanan Arumugam

Let us talk about Technologies

Category Archives: .Net

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated


When I tried to send an email from .Net code, I got the following exception.

Exception

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

Solution

This was because the mail was sent from the office network. By default the credentials in the SmtpClient object is null. The issue was resolved by setting SmtpClient.UseDefaultCredentials to true.

mailClient.UseDefaultCredentials = true;

Sending a simple mail from .Net code


Sending mails from .net code is very easy. System.Net.Mail namespace provides classes that support mail.

At a high level, there are only two things we need to do.

  1. Construct a MailMessage object.
  2. Use a SMTPClient object to send the MailMessage object constructed in the previous step.

 

Following are the steps to send a simple mail.

Step 1: Create a MailMessage object

Create a MailMessage object.

MailMessage message = new MailMessage();

 

Step 2: Specify the from and to addresses

From and To addresses can be specified in the constructor itself. If not done in constructor, it can be done at a later point using the MailMessage.From and MailMessage.To properties.

 

Step 3: Specify Subject

Subject can also be specified through the constructor. If not done in constructor, assign a subject string to MailMessage.Subject property.

 

Step 4: Create the body/content

The body of the mail should be a string. This could be a plain text or an HTML. By default the plain text is assumed to be the type of the body content.

If you create the body using html, set MailMessage.IsBodyHtml property to true.

 

Step 5: Create SmtpClient object and use the Send method

Create the mail client and specify the SMTP host for it. Set the SmtpClient.UseDefaultCredentials to true.

Then use the SmtpClient.Send() method to send the MailMessage object we built in the previous steps.

 

Code snippet to send a sample mail

private static void Main(string[] args)
{
    MailMessage message = new MailMessage(@"saravanandss@gmail.com",
        @"saravanandss@gmail.com");
    message.Subject = "Check SMTP Mail";
    message.Body = @"<html><body><h4>Sample mail body.</h4></body></html>";
    message.IsBodyHtml = true;
    using (SmtpClient mailClient = new SmtpClient())
    {
        mailClient.Host = @"smtp.mysite.com";
        mailClient.UseDefaultCredentials = true;
        mailClient.Send(message);
    }
}

Read a CSV file with Linq


I just wanted to post a small code snippet, for future reference, that reads a CSV file into List of string arrays.

rawFile = (from line in File.ReadAllLines(fileName).AsParallel()
            select line.Split(',')).ToList();

File.ReadAllLines() reads all the lines from the csv into array of comma separated strings. Each line is split based on the comma into an array of strings. AsParallel() attempts to process the whole operation with multiple parallel threads.

Error: Schema with target namespace could not be found.


I was debugging a WSDL by downloading it and its reference XSDs in to my local machine. I got the following exception when I used SVCUtil

Exception

Error: Schema with target namespace ‘http://xmlns.oracle.com/Common/schemas/GetEmployeesPayrateRequest.V1′ could not be found.

Solution

We get this exception because the svcutil for some reason is not finding the referenced schema in the local disk. To solve it, try copying the xsd contents and place them as inline schema under <wsdl:types /> tag.

  <wsdl:types>
    <!--<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:import namespace="http://xmlns.oracle.com/Common/schemas/GetEmployeesPayrateRequest.V1" 
                  schemaLocation="GetEmployeePayrateRequest.v1.xsd"/>
      <xsd:import namespace="http://xmlns.oracle.com/Common/schemas/GetEmployeesPayrateResponse.V1" 
                  schemaLocation="GetEmployeePayratesResponse.v1.xsd"/>
    </xsd:schema>-->
    <xsd:schema elementFormDefault="unqualified" targetNamespace="http://xmlns.oracle.com/Common/schemas/GetEmployeesPayrateRequest.V1"
            xmlns="http://xmlns.oracle.com/Common/schemas/GetEmployeesPayrateRequest.V1" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="GetEmployeesPayrateRequest">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="EMPLID" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
 
    <xsd:schema elementFormDefault="qualified"
            targetNamespace="http://xmlns.oracle.com/Common/schemas/W_GENERIC_RESPONSE8.v1"
            xmlns="http://xmlns.oracle.com/Common/schemas/W_GENERIC_RESPONSE8.v1"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="GetEmployeePayratesResponse">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element maxOccurs="unbounded" minOccurs="0" name="JobRow">
              <xsd:complexType>
                <xsd:sequence>
                  <xsd:element name="EmployeeId" type="xsd:string"/>
                  <xsd:element name="EmployeeName" type="xsd:string"/>
                  <xsd:element minOccurs="0" name="EffectiveDate" type="xsd:date"/>
                  <xsd:element name="HourlyRt" type="xsd:string"/>
                  <xsd:element name="DepartmentId" type="xsd:string"/>
                </xsd:sequence>
              </xsd:complexType>
            </xsd:element>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
  </wsdl:types>

Note that usually the WSDL will generate the <xsd:schema/> tag inside <wsdl:types /> element, and will fill it with multiple imports for every reference types. This has to be replaced by the actual schema definitions. I have just commented it out to show where the replacement has to happen.

Entity Object as Data Contracts in WCF service


I have come across an interesting issue recently while I used Entity Objects in WCF. Before explaining the actual issue, let me explain a few concepts of serialization.

Entity Object vs. WCF

Entity objects are designed so rich, so that if it is chosen to be used in WCF, WCF would not require additional classes to serve as Data Contracts because the entity objects are usually decorated with the following attributes.

    [EdmEntityTypeAttribute(NamespaceName = "IntradoModel", Name = "ICRecord")]
    [Serializable()]
    [DataContractAttribute(IsReference = true)]
    public partial class ICRecord : EntityObject

EdmEntityTypeAttribute links the class to the conceptual model. It helps the Linq to Entity to recognize this type as a legal entity object. SerializableAttribute says that the object of this type can be serialized if needed. DataContractAttribute on the other hand also means that the the type is seriablizable but, by a special serializer – DataContractSerializer.

Note that the classes are partial, so just incase we need more members in the Data Contract, we can always write the partial class with additional members and extend it.

 

Some Concepts of Serialization

There are differences in the way the regular serializers (XmlSerializer, BinaryFormatter, SoapFormatter) and the DataContractSerializer chose the members to serialize. For example consider the following class.

public class SampleClass
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
 
    public int Sum { get; set; }
    public int Product { get; set; }
}

If we serialize an object of the above type, we would get something like below.

<SampleClass>
  <Number1>2</Number1>
  <Number2>2</Number2>
  <Number3>2</Number3>
 
  <Sum>6</Sum>
  <Product>8</Product>  
</SampleClass>

Serialization is usually a costly process, in terms of size, space, or transmission overhead. So its usual that you’d try to ignore some of the members during serialization without losing information. In our example, the information is carried through Number1, Number2, and Number3. But Sum and Product can always be calculated from the numbers at any point of time. So we can ignore them during serialization to save space, size and transmission overheads.

 

Opt-in vs. Opt-out method of serialization

The usual serializers, XmlSerializer, BinaryFormatter, and SoapFormatter works in the Opt-Out method. This means that all the members would be a part of the serialization unless you particularly ignore some. XmlIgnoreAttribute, NonSerializedAttribute, SoapIgnoreAttributes are the ones used to opt-out a member from getting serialized.

[Serializable]
public class SampleClass
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Sum { get; set; }
    
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Product { get; set; }
}

On the other hand DataContractSerializer, works in the Opt-in method. This means that during the serialization only the members marked with DataMemberAttribute would be serialized. Members without the attribute would be ignored during the serialization. Here we are opting-in what we want.

[Serializable]
[DataContract]
public class SampleClass
{
    [DataMember]
    public int Number1 { get; set; }
    [DataMember]
    public int Number2 { get; set; }
    [DataMember]
    public int Number3 { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Sum { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Product { get; set; }
}

 

Possible Issue in using Entity Objects as Data Contracts

I found the following exception when I tried using the Entity Objects as Data Contracts.

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Usually an Entity Object contains the following structure. (We can find the structure of the entity model in Entities.Designer.cs)

    • Factory Method to create an object of its own type.
    • Primary Properties
    • Navigation Properties

Here factory method is not going to be part of the serialization, since its not a property. Primary and Navigation Properties would be part of serialization.

Primary properties provide all the information that you might need from the object. Navigation properties are to help the entity users for accessing the related tables/objects. So it doesn’t have the significance in serialization.

So Navigation Properties need not take part in serialization. XmlSerializer, and SoapFormatter would ignore them, but DataContractSerializer would not (I guess it’s a miss from Microsoft developers group or may be intentional). This is due to the attributes placed on these Navigation properties.

[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("MyModel", 
    "FK_ICRun_ICFile", 
    "ICFile")]
public ICFile ICFile
{
    get{

Reason for the exception

Usually the entity object uses the concept of Lazy Loading. In your code you’d be filling the object by using an object context, and close the context. But this would only fill the primary properties. Navigation properties would be filled only if you need them when you explicitly access them.

using (var context = new IntradoEntities())
{
    return context.ICFiles.Where(record =>
        (FileStatus)record.Status == FileStatus.Error).ToList();
}

When the DataContractSerializer encounters a navigation property, it would try to retrieve it during the runtime. But at the time of serialization Object Context would not be alive, so we end up with the exception.

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Even the Eager Loading, the issue wouldn’t be over since there’s always a limit for the depth of objects during Soap transmission.

Solution

The solution is simple. Remove the DataMemberAttribute from the navigation properties.

To avoid any accidents of removing useful members from serialization, make sure you remove DataMemberAttribute only to those properties within the #region named as Navigation Properties.

I hope we’ll get a better Entity Framework version next time.