Tuesday, May 1, 2012

Saving multiple records in SQL database through XML file

XML has been widely accepted as a platform independent mechanism for transferring the data between loosely coupled systems.For example, if documents are represented in XML, it is very easy to write a DOM or XPATH query to extract the contents of  each section,element and the value.The most common practice is to store preferences of the user record in the database.
If a registered user of a website configures his porfile.Like Theme,Background Images,Accessibilty settings.

Using below code snippet,you can pass a XML document to the stored procedure and save it into the database.This approch greatly improves the performance over inserting single record at a time.It avoids the over head of opening and closing the connection multiple times.

Sample XML document.


<employees>
<employee>
<id>1</id>
<firstname>shree</firstname>
<lastname>gaanji</lastname>
</employee>
<employee>
<id>2</id>
<firstname>manjunath</firstname>
<lastname>gaanji</lastname>
</employee>
<employee>
<id>3</id>
<firstname>sunita</firstname>
<lastname>gaanji</lastname>
</employee>
</employees>

And the below SP is used for parsing the sample XML document and insert it into the database.

CREATE  PROCEDURE [dbo].[insertemployees]
(
  @employees xml
)
as
    BEGIN
        INSERT INTO dbo.employees(id, firstname, lastname)
        SELECT
                      e.value('(id)[1]', 'int') as 'ID',
                      e.value('(firstname)[1]', 'Varchar(50)') as 'firstname',
                      e.value('(lastname)[1]', 'varchar(50)') as 'lastname'
        FROM @employees.nodes('/employees/employee') as emp(e)
    END

Wednesday, April 18, 2012

Sorting an unordered list in javascript


In one of my recent project I come  across sorting  an unordered list on client side without post backing the whole page.The below code snippet will explain the logic to sort the unordered list(ul) using java-script.

The below code snippet is tested and it works fine.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function sortUnorderedList(ul, sortDescending) {
            //if (typeof ul == "String")
            ul = document.getElementById(ul);

            // Idiot-proof, remove if you want
            if (!ul) {
                alert("The UL object is null!");
                return;
            }

            // Get the list items and setup an array for sorting
            var lis = ul.getElementsByTagName("li");
            var vals = [];

            // Populate the array
            for (var i = 0, l = lis.length; i < l; i++)
                vals.push(lis[i].innerHTML);

            // Sort it
            vals.sort();

            // Sometimes you gotta DESC
            if (sortDescending)
                vals.reverse();

            // Change the list on the page
            for (var i = 0, l = lis.length; i < l; i++)
                lis[i].innerHTML = vals[i];
        }
    </script>
</head>
<body>
    <div>
        <ul id="sortlist">
            <li>apple</li>
            <li>banana</li>
            <li>car</li>
            <li>dog</li>
        </ul>
        <button id="btn" value="ASort" onclick="sortUnorderedList('sortlist',false)">
           Ascending</button>
    <button id="Button1" value="DSort" onclick="sortUnorderedList('sortlist',true)">
        Descending</button></div>
</body>
</html>


References - http://stackoverflow.com/questions/9868375/sorting-columns-inside-a-list-alphabetically-using-jquery

Saturday, February 11, 2012

ಪ್ರೇಮಿಗಳ ದಿನ



ಅದೋ ನೋಡಲ್ಲಿ ಮತ್ತೊಮೆ ಬಂದಾಯಿತು ,ಪ್ರೇಮಿಗಳ ದಿನ.
ಈ ಸಾರಿಯಾದರು,ಅವಳಿಗೆ ತಪ್ಪದೆ ಹೇಳಿಬಿಡು ಎಂದು ಪೀಡಿಸಿತು ನನ್ನ ಈ ಮನ.


ಸರಿ! ಎಂದು ಹೇಳಿ. ಬರೆದಿಟ್ಟೆ ನಾ ನೂರಾರು ಹನಿಗವನ.
ಸಮೀಪಿಸಿದಂತೆ ಆ ಪ್ರೇಮಿಗಳ ದಿನ, ನಡುಗುತಿದೆ ನನ್ನ ಈ ಮಯಿ,ಮನ.


ಆ ದೇವರಲ್ಲಿ ನನ್ನದೊಂದೇ ನಮನ,  ಬಾಡುವ ಮುನ್ನ ಈ ನನ್ನ ಯವ್ವನ,
ಹೇಳುವ ದ್ಯೆರ್ಯ ನೀಡೆಂದು ಬೇಡುತಾ,ಮುಗಿಸುವೆ ಈ ನನ್ನ ಪುಟ್ಟ ಕವನ.








Monday, February 6, 2012

Integrating Google(gmail) calendar in ASP.NET application

The below article will provide you a small snippet of code,that can be used to intgrate the gmail calendar in you asp.net application.Basically,You need to pass the parameters like Username,Password,StartDate,EndDate to retrieve the appointment list.


I have created a custom class"CalendarInfo" to hold the appointment list.

"CalendarInfo" class contains the below properties.

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Serialization;

[Serializable()]

public class CalendarInfo

{

private string _location;

private DateTime _startTime;

private DateTime _endTime;

private string _subject;

private string _body;

 



public string Location

{

get { return _location; }

set { _location = value; }

}

public DateTime StartTime

{

get { return _startTime; }

set { _startTime = value; }

}

public DateTime EndTime

{

get { return _endTime; }

set { _endTime = value; }

}

public string Subject

{

get { return _subject; }

set { _subject = value; }

}

public string Body

{

get { return _body; }

set { _body = value; }

}

}



private void GoogleCalendar(string username, string password, DateTime startdate, DateTime enddate)

{

       
List<CalendarInfo> _calendarEvents = new List<CalendarInfo>();
//pass logged in user credentials

CalendarService service = new CalendarService("exampleCo-exampleApp-1");

service.setUserCredentials(username, password);

EventQuery query = new EventQuery();

query.Uri = new Uri("https://www.google.com/calendar/feeds/default/private/full");

query.SortOrder = CalendarSortOrder.ascending;

try

{

EventFeed events = service.Query(query);

int n = events.Entries.Count;

if (events.Entries.Count > 0)

{

int x = 0;

string mes = string.Empty;

while (x < n)

{

Google.GData.Calendar.
EventEntry entry = (Google.GData.Calendar.EventEntry)events.Entries[x];

if (entry.Times[0].StartTime.Date >= startdate && entry.Times[0].EndTime.Date <= enddate)

{



CalendarInfo objinfo = new CalendarInfo();

objinfo.Subject = entry.Title.Text;

objinfo.Body = entry.Content.Content;

objinfo.StartTime =
Convert.ToDateTime(entry.Times[0].StartTime);

objinfo.EndTime = Convert.ToDateTime(entry.Times[0].EndTime);

objinfo.Location = entry.Locations[0].ValueString;

_calendarEvents.Add(objinfo);



}

x = x + 1;

}

}

}

catch (GDataRequestException ex)

{
  //write the logic to log the exception
}

catch (GDataBatchRequestException ex)

{
    //write the logic to log the exception
}

catch (ArgumentOutOfRangeException ex)

{
    //write the logic to log the exception
}

catch (ClientFeedException ex)

{
    //write the logic to log the exception
}

catch (AuthenticationException ex)

{
    //write the logic to log the exception
}

}

Sunday, February 5, 2012

Integrating Outlook calendar in .NET application -Part-2

Let me tell you,I am not an expert on integrating Outlook calendar in .NET application.Recently,In one of my project.I have come across integrating outlook in our application.So,Thought of sharing the snippet of code with you.That may save a piece of your time.

The below code,will explian you how to integrate the outlook by EWS method.Exchange Web Services (EWS) for Microsoft Exchange 2007 provides a quick an easy way to interface with Exchange data with your custom application.The Exchange Web Services module works on the concept of creating a soap message and sending it to the Exchange that will tell the server what you’re looking for and then give you back a soap response.

Right click on your ASP.NET application and choose add web reference option.

http://<YourExchangeServer>/EWS/Services.wsdl

The below snippet of code reads the Outlook appoitnments.

Just to keep the code clean and make it reusable,I kept the  exchage server details in config file.

Ex :-
Settings from web.config file

 <add key="ExServer" value="http://<YourExchangeServer>/EWS/Exchange.asmx"/>

The below code reads the appointments fom the exchange server.
 string username = "Username";
 string password = "Password";
 string email = "
Username@example.com";
DateTime startdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime temp = new DateTime(startdate.Year, startdate.Month + 1, 1);
DateTime enddate = temp.AddDays(-1);



private void OutlookCalendar(string username, string password, DateTime startdate, DateTime enddate, string outlook_email)

{

ExchangeServiceBinding esb = new ExchangeServiceBinding();

esb.Url = Convert.ToString(ConfigurationManager.AppSettings["ExServer"]);

esb.Credentials = new NetworkCredential(username, password, Convert.ToString(ConfigurationManager.AppSettings["domain"]));

// Form the FindItem request.

FindItemType findItemRequest = new FindItemType();

CalendarViewType calendarView = new CalendarViewType();

calendarView.StartDate = startdate;//DateTime.Now.AddDays(-1);

calendarView.EndDate = enddate; //DateTime.Now.AddDays(1);

calendarView.MaxEntriesReturned = 100;

calendarView.MaxEntriesReturnedSpecified =
true;

findItemRequest.Item = calendarView;

// Define which item properties are returned in the response.

ItemResponseShapeType itemProperties = new ItemResponseShapeType();

// Use the Default shape for the response.

//itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;

itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

findItemRequest.ItemShape = itemProperties;

DistinguishedFolderIdType[] folderIDArray =

new DistinguishedFolderIdType[1];

folderIDArray[0] = new DistinguishedFolderIdType();

folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;


folderIDArray[0].Mailbox = new EmailAddressType();

folderIDArray[0].Mailbox.EmailAddress = outlook_email;

//}

findItemRequest.ParentFolderIds = folderIDArray;

// Define the traversal type.

findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

try

{

// Send the FindItem request and get the response.

FindItemResponseType findItemResponse =

esb.FindItem(findItemRequest);

// Access the response message.

ArrayOfResponseMessagesType responseMessages =

findItemResponse.ResponseMessages;

ResponseMessageType[] rmta = responseMessages.Items;

int folderNumber = 0;

foreach (ResponseMessageType rmt in rmta)

{

// One FindItemResponseMessageType per folder searched.

FindItemResponseMessageType firmt =

rmt as FindItemResponseMessageType;

if (firmt.RootFolder == null)

continue;

FindItemParentType fipt = firmt.RootFolder;

object obj = fipt.Item;

// FindItem contains an array of items.

if (obj is ArrayOfRealItemsType)

{

ArrayOfRealItemsType items =

(obj as ArrayOfRealItemsType);

if (items.Items == null)

{

folderNumber++;

}

else

{

foreach (ItemType it in items.Items)

{

if (it is CalendarItemType)

{

CalendarItemType cal = (CalendarItemType)it;

CalendarInfo ce = new CalendarInfo();

ce.Location = cal.Location;

ce.StartTime = cal.Start;

ce.EndTime = cal.End;

ce.Subject = cal.Subject;

ce.Body = GetMeetingBody(esb, cal);

_calendarEvents.Add(ce);

}

}

folderNumber++;

}

}

}

}

catch (Exception e)

{

throw;

}

finally

{

}


}

References-
1. http://blogs.visoftinc.com/2008/03/20/Using-Exchange-Web-Services-2007-The-Basics/
2. http://weblogs.asp.net/psperanza/archive/2008/03/18/getting-calendar-items-using-exchange-web-services.aspx

Integrating Outlook calendar in .NET application -Part1

Micorsoft for it's major applications provides a way of integrating with the exteranal application,Like exposing it as a COM component or throw web service.Now,In my case.I want to integrate the MS Outlook in a .NET Application.

As I know, Basically there are 4 ways to acieve it.
  1. Using Microsoft.Office.Interop.Outlook.dll
  2. WEDEV
  3. Exchange web services.
  4. Active directory services interface.

The types and members of the Microsoft.Office.Interop.Outlook namespace provide support for interoperability between the COM object model of Microsoft Outlook 2010 and managed applications that automate Outlook.

Outllok DLL reference  is the best suited option of the stand alone applications.

Right click on the project and choose add reference option.



Add the namspace reference,In your class file.
using  Microsoft.Office.Interop.Outlook;

In the below snippet of code,I am reading the Outlook Appointments for the given month.
private void OutlookCalendar(DateTime dt)

{

DataTable dtmaster = new DataTable();
try

{

Microsoft.Office.Interop.Outlook.Application oApp = null;

Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;

Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;

Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;

oApp = new Microsoft.Office.Interop.Outlook.Application();

mapiNamespace = oApp.GetNamespace("MAPI");

CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);

outlookCalendarItems = CalendarFolder.Items;

outlookCalendarItems.IncludeRecurrences = true;

string mes = string.Empty;

foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)

{

if (item.IsRecurring == false)

{

DateTime temp = new DateTime(dt.Year, dt.Month + 1, 1);

DateTime enddate = temp.AddDays(-1);

if (item.Start.Date >= dt && item.Start.Date <= enddate)

{

DateTime startDt = item.Start;

DateTime endDt = item.End;

dtmaster.Rows.Add(item.Subject, item.Body, startDt, endDt, startDt.ToString("hh:mm") + " - " + endDt.ToString("hh:mm"), item.Location);

}

}

}

}

catch (System.Exception ex)

{

//logic to log the exception to your error log file

}

}

In my next blog,I will explain how to integrate outlook in ASP.NET application throw Exchange web service method(EWS).