Blog from Saravanan Arumugam

Let us talk about Technologies

Monthly Archives: April 2012

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;
Advertisements

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.

Select All check box with jQuery


Select All check box is usually the checkbox at the top of grid, checking which would check every checkbox in the table/grid. I am going to talk about the check box (imagine check boxes in place of the first column with X) with gray background at the top of the following table.

X Shift Date Employee ID Code Duration Status
x 12/1/2011 232 Read-only User 3 years Active
x 12/1/2011 12 Super User 7 years Active

When I check the Select All checkbox, it should check all the checkboxes in every row. When I uncheck the Select All checkbox, all the checkboxes in the table should be unchecked.

Let me present the code here first and give the explanation below.

    $("input[type='checkbox'].checkAll").bind('change', function () {
        var checkAll = $(this).prop('checked');
 
        $("table:has(input[type='checkbox'].checkAll) input[type='checkbox']")
        .each(function (index, domElement) {
            if ($(domElement).is("input[type='checkbox']")) {
                $(domElement).prop('checked', checkAll);
            }
        });
    });

The script is kept in the shared js file.

The html of the Select All check box is,

<input class=”checkAll” id=”checkAll” name=”checkAll” type=”checkbox” value=”true” /><input name=”checkAll” type=”hidden” value=”false” />

Note that the checkbox never refers to any script. But the script refers to the checkbox by recognizing its class name “checkAll”.

 

Code Explanation

Step 1. Identify the Check All checkbox

$(“input[type=’checkbox’].checkAll”)

The first line of the code starts with a selector ($() is referred to be a selector. It selects the controls that matches its parameters). The selector parameter conveys 3 messages.

  1. input – The selected object should be an input element.
  2. [type=’checkbox’] – The selected object should have an attribute called type and its value should be ‘checkbox’.
  3. .checkAll – The selected object should have the class name checkAll.

The selector usually follows the same syntax that CSS use to identify elements.

 

Step 2. Attach an event handler for onchanged event of Select All checkbox

.bind(‘change’, function () { }

bind() method attaches an event handler to an element’s event. First parameter to the bind() method is the event name and the second parameter is the event handler delegate.

 

Step 3. Store the current state of the Select All checkbox

var checkAll = $(this).prop(‘checked’);

The code above gets the current state (true/false to represent checked/unchecked state) of Select All check box.

$(this) represents the control for which containing function is delegated to. In our case, this refers to the Select All checkbox.

 

Step 4. Select all the checkboxes contained in the table where Select All is housed

$(“table:has(input[type=’checkbox’].checkAll) input[type=’checkbox’]”)

By writing a selector with $(“input[type=’checkbox’]”) we can select all the checkboxes on the page. But we don’t want to check or uncheck something that doesn’t belong to the table containing the Select All checkbox. So in the selector, precede the input[type=’checkbox’] with table:has(input[type=’checkbox’].checkAll). By doing this, we are saying that the container for the input is a table, and the table has the checkbox with the class name checkAll.

 

Step 5. Iterate through all the elements and assign the checked status

.each(function (index, domElement) {

         if ($(domElement).is(“input[type=’checkbox’]”)) {

                 $(domElement).prop(‘checked’, checkAll);

         }

});

Note that each() method takes a function having 2 parameters. As their name suggest, the first one is the index of the element and the second one is the element itself.

if() condition is written just to double check the type of the element, but this is optional at this point.

prop() method is capable of both checking and assigning a value. We are using the prop method on the element to assign the value to the checked property.

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.