Wednesday, August 1, 2018

Descriptive Statstics


Descriptive Statistics


Datasets - List of things or bunch of numbers

Examples:

                Weight of 20 Students
                122, 118, 56, 54, 77, 90, 116, 88, 72, 56
                112, 123, 55, 74, 87, 100, 96, 68, 55, 61

                Hair Color of 20 Students
                Brown, Red, Black, Black, Black, Black, Red, Brown, Red, Black
                Black, Red, Brown, Black, Black, Red, Brown, Brown, Brown, Black
               
Sample Size (n) = total count of Observations of Dataset   (ex: n=20 in above cases)

Data Classifications:

 Discrete:

Have natural categories (Ex: Hair color of 20 students Red, Brown, Black)

 Continuous:

Have continuous numerical data (Ex: Weight of 20 Students)

Distribution of Discrete Datasets:

Simply classify the data/observations into categories
               
Eg: Left Handed Person (L)/ Right Handed Person (R)
L, R, L, L, L, R, R, R, R, L
R, L, R, L, R, L, L, L, R, L
               
Only have 2 categories
Right(R) = 9
Left (L) = 11
               

Inference:

Sample Proportion (occurrence of Right handed people in sample): 9/20
Sample Proportion (occurrence of Left handed people in sample): 11/20
Left handed people are more





Distribution of Continuous Datasets:

No natural values, hence create categories


Steam Leaf Plot:

Create Category1 as 2Digit. All values falling under this interval will have first 2 digits 12 or 13 or 14 or 15. This is called “Stem”. “Leaf”= All digits left out of Stem.
Example:
126 => Stem =12; Leaf=6
1298 => Stem=12; Leaf=98
138=>Stem=13; Leaf=8

Applying the 2Digit technique on above data:


Again classify the “Stems” as Stem1= 0-4 digits under one category and Stem2=5-9 digits as other

Dot Plot:

Draw a line (scale) of maximum and minimum range and plot the values
Observations with same value put second dot above first dot.

For the example data of Etruscan:

Comparative Dot Plots





5-Point method Descriptive Statistics–Continuous data:


Minimum = 126
Maximum=158
Range=Maximum – Minimum = 32
Range also termed as measure of scale/dispersion /noise
Outliers – Points far from rest of data
Median = Robust in statistics. Center item in sorted list
If n=25 then median = (n+1)/2 = 26/2=13th item = 146

(25%) First Quartile (Q1) = Center point of 1st half up to median (n/4)
50% Quartile (Q2) = 50% = n/2
(75%) Third Quartile (Q3) = Center point of last half from median (n/8)
Inter Quartile range (IQR) = Q3 – Q1
As per 5 Point method for the above dataset
Min=126, Q1=146, Median=142, Q3=150, Max=158, Range=32
Stem Leaf Plot:
Graphical representation of values which will easily define 5 point method.
                                |-------------------              -------|
Min----------       Q1                                    Q3----------Mx
                                |---------------------------|

Outliers and Box Plot
Points not belong to the range or dataset is termed as outliers
               

Comparing datasets:

Shift of 13 between Etruscan and Italian is the Medians out of 5 Points (146-133)=13. This is termed as Location Problem

Measure of Center:

Sample Mean – average (sum of numbers / number of items)
Median =11
Sample Mean = 84/7 =12
Mean is sensitive to outliers

s=standard deviation
Walsh Average/Hodges-Lehmann Estimates:
For a simple data sets order and make tables as rows and columns.
For pair of data points we calculate only once. Calculate average pairs associated with row & column elements.

Measure of Scale of Noise:

Range, IQR
Variance = Measure of deviation from mean

Set1=11, 18, 6,4,8,15,22
Sample mean =12
Deviations =-1, 6, 6,-8, 3, 10 (xn-12)
Squared Deviations= s2   =1, 36, 36, 64, 9, 100 =246/6=41
s=  =6.4









               











               

               
               
               
               


Monday, March 26, 2018

Integration of Exchange using EWS-Managed API


/*Only for reference    NOT A WORKING SAMPLE*/


using Microsoft.Exchange.WebServices.Data;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.Exchange.WebServices.Data.SearchFilter;

namespace  exchangeConsole
{
    class Program

    {

        private static string ContentsSyncState;
        private static string FolderSyncState;

        private static ChangeCollection<ItemChange> ItemChangeCollection;
        private static ChangeCollection<FolderChange> FolderChangeCollection;
        private static AutoResetEvent Signal;
        private static StreamingSubscription StreamingSubscription;
        private static PullSubscription PullSubscription;
        private static string PullSubscriptionId;
        private static string WaterMark;
        static bool FirstPull = false;
        private static int WaitTime = 3;

        static ExchangeService service = EService.ConnectToService(UserDataFromConsole.GetUserData(true));

        // Set the root folder to sync. This must be one of the WellKnownFolderName values.
        private static FolderId RootSyncFolder = WellKnownFolderName.Calendar;
        static DbContext dbContext = new demoentitees();



        static void Main(string[] args)
        {


            var syncStates = dbContext.Set<SyncState>();

            if (syncStates.Count() != 0 && syncStates.Where(x => x.IsFolder == true && x.CreatedBy != "testxxx") != null && syncStates.Where(x => x.IsFolder == true && x.CreatedBy != "testxxx").Count() > 0)
            {
             
                FolderSyncState = syncStates.Where(x => x.IsFolder == true && x.CreatedBy != "testxxx").OrderByDescending(x => x.Id).FirstOrDefault().SyncString;
                ContentsSyncState = syncStates.Where(x => x.IsFolder == false && x.CreatedBy != "testxxx").OrderByDescending(x => x.Id).FirstOrDefault().SyncString;
            }

            else
            {
                FirstPull = true;
                FolderSyncState = null;
                ContentsSyncState = null;
            }



         

            // Retrieve the initial folder hierarchy, using rootSyncFolder as the root folder.
            FolderSyncState = SyncFolders(service, FolderSyncState, RootSyncFolder);

            //  Retrieve the initial contents of the rootSyncFolder.
            ContentsSyncState = SyncContents(service, ContentsSyncState, RootSyncFolder);



            // After the initial sync, wait for notifications of new or changed items.
            // StreamingSubscription = SetStreamingNotifications(service, ContentsSyncState, RootSyncFolder);
            //Restart:
            //do
            //{
            //    SetPullNotifications(service, WaterMark, RootSyncFolder);
            //} while (PullSubscription.MoreEventsAvailable.HasValue && !PullSubscription.MoreEventsAvailable.HasValue);

            //Signal = new AutoResetEvent(false);
            //PullSubscription.Unsubscribe();
            // Wait for the application to exit.
            // Signal.WaitOne();

            //Console.WriteLine("Enter 'y' or 'N' ");

            //string key = Console.ReadLine();
            //if (key == "y"|| key=="Y")
            //    goto Restart;

            Console.Read();

        }


        // Synchronize the contents of the rootSyncFolder folder.
        static string SyncContents(ExchangeService service, string cSyncState, FolderId rootSyncFolder)
        {
            //Console.WriteLine("--------");
            //Console.WriteLine("Starting content sync on the following folder");
            //Console.WriteLine("FolderId: {0}", rootSyncFolder);
            //Console.WriteLine("--------");

            bool moreChangesAvailable = false;

            do
            {

                // Get a change collection of all items in the rootSyncFolder by calling SyncFolderItems
                // repeatedly until no more changes are available.
                // The folderId parameter must be set to the same folder ID as the previous synchronization call.
                // The propertySet parameter is set to IdOnly to reduce calls to the Exchange database,
                // because any additional properties result in another call to the Exchange database.
                // The ignoredItemIds parameter is set to null, so no items are ignored.
                // The maxChangesReturned parameter is set to return a maximum of 500 items (512 is the default).
                // The syncScope parameter is set to Normal items, so associated items will not be returned.
                // The syncState parameter is set to the content sync state. When this method is called
                // on a new or empty mailbox, the value is null. If the method has been called before,
                // the cSyncState value contains the value previously returned by the server.
                ItemChangeCollection = service.SyncFolderItems(rootSyncFolder, PropertySet.IdOnly, null, 500, SyncFolderItemsScope.NormalItems, cSyncState);


                // Save the sync state for use in future SyncFolderItems requests.
                // The sync state is used by the server to determine what changes to report
                // to the client.
                cSyncState = ItemChangeCollection.SyncState;

                // If the count of changes is zero, there are no changes to synchronize.
                if (ItemChangeCollection.Count == 0)
                {
                    //Console.WriteLine("There are no items to synchronize.");
                    Console.WriteLine("--------");


                }

                // Otherwise, write all the changes included in the response
                // to the console.
                else
                {

                    foreach (ItemChange ic in ItemChangeCollection)
                    {
                        //Console.WriteLine("ItemChange.ChangeType: " + ic.ChangeType.ToString());
                        //Console.WriteLine("ItemChange.ItemId: " + ic.ItemId.UniqueId);
                        //Console.WriteLine("--------");


                        using (var ctx = new demoEntities())
                        {
                            var std = new SyncState()
                            {
                                 //save
                            };
                            ctx.SyncStates.Add(std);
                            ctx.SaveChanges();


                        }

                    }
                }

                // Determine whether more changes are available on the server.
                moreChangesAvailable = ItemChangeCollection.MoreChangesAvailable;

                // Send the ItemChangeCollection to ProcessItems to actually retrieve the messages and changes.
                ProcessItems(ItemChangeCollection);
            }

            while (moreChangesAvailable);

            Console.WriteLine("Finished content sync on the following folder");
            Console.WriteLine("FolderId: {0}", rootSyncFolder);
            Console.WriteLine("--------");

            return cSyncState;
        }

        static string ItemIdSearch(string Id, string subject, DateTime sent)
        {
            ItemView view = new ItemView(1000);

            //List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>();
       
            //////searchANDFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema., ".Note.Exchange"));
            ////searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subject));
            ////searchANDFilterCollection.Add(new SearchFilter.IsEqualTo(AppointmentSchema.MeetingRequestWasSent,true));

            ////searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeSent, sent));
            ////searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeSent, sent.AddHours(24)));

            string id = string.Empty;

         //   SearchFilter searchANDFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray());


            var results = service.FindItems(WellKnownFolderName.Calendar, view);
            foreach (var item in results)
            {
                var synstatesid = dbContext.Set<SyncState>().ToList().Where(x => x.SyncString == ContentsSyncState && x.Id == item.Id.UniqueId && x.IsFolder == false)
                    .OrderByDescending(x => x.Id).FirstOrDefault();
                if (synstatesid != null)

                    id = synstatesid.EWSId;
            }

            return id;
        }

        private CalendarFolder FindNamedCalendarFolder(string name)
        {
            FolderView view = new FolderView(100);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;

            SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.FolderClass, "1ppointment");

            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Root, sfSearchFilter, view);
            return findFolderResults.Where(f => f.DisplayName == name).Cast<CalendarFolder>().FirstOrDefault();
        }


        static void ESave(string ItemId, string type = "email")
        {


            if (type == "email")
            {
                var msg = Item.Bind(service, ItemId);
                using (var ctx = new EWS_DemoEntities())
                {

                    var std = new EmailMessasge()
                    {
                        ///asave
                    };
                    ctx.EmailMessasges.Add(std);
                    ctx.SaveChanges();

                }
            }
            else
            {
                Appointment met = Appointment.Bind(service, ItemId);
                using (var ctx = new demoEntities())
                {

                    var std = new Meeting()
                    {
//                        save

                    };
                    ctx.Meetings.Add(std);
                    ctx.SaveChanges();

                }

            }



        }

        // Get the items and changes in the root folder.
        static void ProcessItems(ChangeCollection<ItemChange> icc)
        {

            // Create a variable for all the new items in the ItemChangeCollection.
            var newItems = from ic in icc
                           where ic.ChangeType == ChangeType.Create
                           select ic.Item;

            // Get the properties for each item, so that they can be created on the client.
            foreach (var item in newItems)
            {
                service.LoadPropertiesForItems(newItems, PropertySet.FirstClassProperties);
                //Console.WriteLine("New item, all properties loaded");
                //Console.WriteLine("Subject: {0}", item.Subject);
                //Console.WriteLine("ParentFolderId: {0}", item.ParentFolderId);
                //Console.WriteLine("DateTimeCreated: {0}", item.DateTimeCreated);
                //Console.WriteLine("--------");
                // TODO: Create the messages on the client by using the properties
                // returned from LoadPropertiesForItems.

                string fid = ItemIdSearch(item.Id.UniqueId, "test", new DateTime(2018, 03, 14));
                if (!string.IsNullOrEmpty(fid))
                {
                     Save(fid);
                }

            }

            // Create a variable for all the deleted items in the ItemChangeCollection.
            var deleteItems = from ic in icc
                              where ic.ChangeType == ChangeType.Delete
                              select ic.ItemId;

            // Display the ItemIds to be deleted on the client.
            foreach (var item in deleteItems)
            {
                Console.WriteLine("Delete ItemId: {0}", item);
                Console.WriteLine("--------");
                // TODO: Delete messages on the client by using the ItemIds in deleteItems. 
            }

            // Create a variable for all the items with read state changes in the ItemChangeCollection.
            var readFlagChangeItems = from ic in icc
                                      where ic.ChangeType == ChangeType.ReadFlagChange
                                      select ic.ItemId;

            // Display the ItemIds that have read state changes.
            foreach (var item in readFlagChangeItems)
            {
                //Console.WriteLine("Read flag change to ItemId: {0}", item);
                //Console.WriteLine("--------");
                // TODO: Change the read state of the item saved on the client
                // by using the ItemIds in readFlagChangeItems.
                string fid = ItemIdSearch(item.UniqueId, "ouu", new DateTime(2018, 03, 14));
                if (!string.IsNullOrEmpty(fid))
                {

                     save(fid);
                }
            }

            // Create a variable for all the updated items in the ItemChangeCollection.
            var updateItems = from ic in icc
                              where ic.ChangeType == ChangeType.Update
                              select ic.Item;

            // Display the subject for each updated item.
            foreach (var item in updateItems)
            {
                service.LoadPropertiesForItems(updateItems, PropertySet.FirstClassProperties);
                //Console.WriteLine("Updated item, all properties loaded");
                //Console.WriteLine("Subject: {0}", item.Subject);
                //Console.WriteLine("ParentFolderId: {0}", item.ParentFolderId);
                //Console.WriteLine("DateTimeCreated: {0}", item.DateTimeCreated);
                //Console.WriteLine("--------");
                // TODO: Compare the properties retrieved from LoadPropertiesForItems to the
                // properties on the client and update the client properties accordingly.

                string fid = ItemIdSearch(item.Id.UniqueId, "ouu", new DateTime(2018, 03, 14));
                if (!string.IsNullOrEmpty(fid))
                {
                     save(fid);
                }
            }
        }

        // Get the folder changes in the root folder.
        static void ProcessFolders(ChangeCollection<FolderChange> fcc)
        {

            // Create a variable for all the new folders in the FolderChange ChangeCollection.
            var newFolders = from fc in fcc
                             where fc.ChangeType == ChangeType.Create
                             select fc.FolderId;

            // Get the properties for each folder, so that they can be created on the client.
            foreach (var item in newFolders)
            {
                Folder newFolder = new Folder(service);
                newFolder = Folder.Bind(service, item);
                newFolder.Load();
                //Console.WriteLine("New folder, all properties loaded");
                //Console.WriteLine("Display name: {0}", newFolder.DisplayName);
                //Console.WriteLine("Parent Folder Id: {0}", newFolder.ParentFolderId);
                //Console.WriteLine("--------");

                // TODO: Create the folder on the client by using the properties
                // returned from Load.

                // Call SyncContents and SetStreamingNotifications on the new child folders.
                string ccSyncState = SyncContents(service, null, newFolder.Id);
                //SetStreamingNotifications(service, ccSyncState, newFolder.Id);

            }

            // Create a variable for all the deleted folders in the FolderChange ChangeCollection.
            var deleteFolders = from fc in fcc
                                where fc.ChangeType == ChangeType.Delete
                                select fc.FolderId;

            // Display the FolderIds to be deleted on the client.
            foreach (var item in deleteFolders)
            {
                Console.WriteLine("Delete FolderId: {0}", item);
                Console.WriteLine("--------");
                // TODO: Delete messages on the client by using the FolderIds in deleteFolders.
            }

            // Create a variable for all the updated folders in the FolderChange ChangeCollection.
            var updateFolders = from fc in fcc
                                where fc.ChangeType == ChangeType.Update
                                select fc.Folder;

            // Display the display name for each updated folder.
            foreach (var item in updateFolders)
            {
                Folder folder = Folder.Bind(service, item.Id);
                folder.Load();
                //Console.WriteLine("Updated folder, all properties loaded.");
                //Console.WriteLine("Parent Folder Id: {0}", item.ParentFolderId);
                //Console.WriteLine("Display name: {0}", item.DisplayName);
                //Console.WriteLine("--------");
                // TODO: Compare the properties retrieved from Load to the
                // properties on the client and update the client properties accordingly.
            }
        }

        // When the subscription connection expires, determine whether the subscription should be kept open.
        static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
        {
            // Cast the sender as a StreamingSubscriptionConnection object.         
            StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;

            // Ask the user if they want to reconnect or close the subscription.
            ConsoleKeyInfo cki;
            Console.WriteLine("The StreamingSubscriptionConnection has expired.");
            Console.WriteLine("\r\n");
            Console.WriteLine("Do you want to reconnect to the subscription? Enter Y or N");
            Console.WriteLine("\r\n");
            while (true)
            {
                cki = Console.ReadKey(true);
                {
                    if (cki.Key == ConsoleKey.Y)
                    {
                        connection.Open();
                        Console.WriteLine("Connection open.");
                        Console.WriteLine("\r\n");
                        break;
                    }
                    else if (cki.Key == ConsoleKey.N)
                    {
                        Signal.Set();

                        // Unsubscribe from the notification subscription.
                        StreamingSubscription.Unsubscribe();

                        // Close the connection.
                        connection.Close();
                        break;
                    }
                }
            }
        }

        // Catch and display notification events.
        static void OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            bool callSyncContents = false;
            bool callSyncFolders = false;

            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {

                switch (notification.EventType)
                {
                    case EventType.NewMail:
                        Console.WriteLine("Notification: New mail created");
                        break;
                    case EventType.Created:
                        Console.WriteLine("Notification: Item or folder created");
                        break;
                    case EventType.Deleted:
                        Console.WriteLine("Notification: Item or folder deleted");
                        break;
                    case EventType.Modified:
                        Console.WriteLine("Notification: Item or folder modified");
                        break;
                    case EventType.Moved:
                        Console.WriteLine("Notification: Item or folder moved");
                        break;
                    case EventType.Copied:
                        Console.WriteLine("Notification: Item or folder copied");
                        break;
                }
                // Display the notification identifier.
                if (notification is ItemEvent)
                {
                    ItemEvent itemEvent = (ItemEvent)notification;
                    Console.WriteLine("Notification ItemId: " + itemEvent.ItemId.UniqueId);
                    Console.WriteLine("--------");
                    callSyncContents = true;
                }
                else
                {
                    FolderEvent folderEvent = (FolderEvent)notification;
                    Console.WriteLine("Notification FolderId: " + folderEvent.FolderId.UniqueId);
                    Console.WriteLine("--------");
                    callSyncFolders = true;
                }
            }

            // Delay calling SyncContents and SyncFolders until all notifications have been processed.
            // This will reduce the number of calls to the Exchange database by batching more changes
            // into a single sync call.
            if (callSyncContents == true)
            {
                ContentsSyncState = SyncContents(service, ContentsSyncState, RootSyncFolder);
            }

            if (callSyncFolders == true)
            {
                FolderSyncState = SyncFolders(service, FolderSyncState, RootSyncFolder);
            }
        }


        // Synchronize the folders in the specified root folder.
        static string SyncFolders(ExchangeService service, string FolderSyncState, FolderId rootSyncFolder)
        {
            //Console.WriteLine("Starting folder sync on the following folder");
            //Console.WriteLine("FolderId: {0}", rootSyncFolder);
            //Console.WriteLine("--------");

            // Get a list of all folders under the rootSyncFolder by calling SyncFolderHierarchy.
            // The folderId parameter is the root folder to synchronize.
            // The propertySet parameter is set to IdOnly to reduce calls to the Exchange database,
            // because any additional properties result in another call to the Exchange database.
            // The syncState parameter is set to the folder sync state. When this method is called
            // on a new or empty mailbox, the value is null. If the method has been called before,
            // the FolderSyncState value contains the value previously returned by the server.
            FolderChangeCollection = service.SyncFolderHierarchy(rootSyncFolder, PropertySet.IdOnly, FolderSyncState);

            // Save the sync state for use in future SyncFolderItems requests.
            // The sync state is used by the server to determine what changes to report
            // to the client.
            FolderSyncState = FolderChangeCollection.SyncState;

            // If the count of changes is zero, there are no changes to synchronize.
            if (FolderChangeCollection.Count == 0)
            {
                //Console.WriteLine("There are no new folders to synchronize.");
                //Console.WriteLine("--------");
            }

            // Otherwise, write all the changes included in the response
            // to the console.
            // For the initial synchronization, all the changes will be of type
            // ChangeType.Create.
            else
            {
                foreach (FolderChange fc in FolderChangeCollection)
                {
                    //Console.WriteLine("FolderChange.ChangeType: " + fc.ChangeType.ToString());
                    //Console.WriteLine("FolderChange.FolderId: " + fc.FolderId);
                    //Console.WriteLine("--------");


                    using (var ctx = new DemoEntities())
                    {
                        var std = new SyncState()
                        {
                            //save
                        };
                        ctx.SyncStates.Add(std);
                        ctx.SaveChanges();

                    }
                }

            }

            // Send the FolderChangeCollection to ProcessItems to actually retrieve the messages and changes.
            ProcessFolders(FolderChangeCollection);

            //Console.WriteLine("Finished folder sync on the following folder");
            //Console.WriteLine("FolderId: {0}", rootSyncFolder);
            //Console.WriteLine("--------");

            return FolderSyncState;

        }

        //Subscribe to streaming notifications for all folder and item events in the root folder.
        static StreamingSubscription SetStreamingNotifications(ExchangeService service, string cSyncState, FolderId rootSyncFolder)
        {
            // Subscribe to streaming notifications on the rootSyncFolder and listen
            // for events.
            StreamingSubscription = service.SubscribeToStreamingNotifications(
                new FolderId[] { rootSyncFolder },
                EventType.NewMail,
                EventType.Created,
                EventType.Deleted,
                EventType.Modified,
                EventType.Moved,
                EventType.Copied
                );

            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, WaitTime);
            connection.AddSubscription(StreamingSubscription);
            connection.OnNotificationEvent += OnNotificationEvent;
            connection.OnDisconnect += OnDisconnect;
            connection.Open();

            Console.WriteLine("Now waiting for notifications on the following folder");
            Console.WriteLine("FolderId: {0}", rootSyncFolder);
            Console.WriteLine("--------");

            return StreamingSubscription;

        }

        //Subscribe to streaming notifications for all folder and item events in the root folder.
        static PullSubscription SetPullNotifications(ExchangeService service, string watermark, FolderId rootSyncFolder)
        {


            // Subscribe to streaming notifications on the rootSyncFolder and listen
            // for events.
            PullAgain:
            PullSubscription = service.SubscribeToPullNotifications(
                new FolderId[] { rootSyncFolder }, WaitTime, watermark,
                EventType.NewMail,
                EventType.Created,
                EventType.Deleted,
                EventType.Modified,
                EventType.Moved,
                EventType.Copied
                );
            var events = PullSubscription.GetEvents();

            PullSubscriptionId = PullSubscription.Id;
            if (WaterMark != PullSubscription.Watermark)
            {
                WaterMark = PullSubscription.Watermark;
                goto PullAgain;

            }






            if (events.ItemEvents.Count() > 0)
            {
                // Handle the results of the GetEvents method.
                foreach (ItemEvent itemEvent in events.ItemEvents)
                {

                    switch (itemEvent.EventType)
                    {
                        case EventType.NewMail:
                            EmailMessage message = EmailMessage.Bind(service, itemEvent.ItemId);
                            message.Load();
                            Console.WriteLine("Item new mail: " + message.Subject);
                            //Console.WriteLine("Item Id:" + message.Id);
                            break;
                        case EventType.Created:
                            Item item = Item.Bind(service, itemEvent.ItemId);
                            item.Load();
                            Console.WriteLine("Item Created: " + item.Subject);
                            // Console.WriteLine("Item Id:" + item.Id);
                            break;
                        case EventType.Deleted:
                            Item d = Item.Bind(service, itemEvent.ItemId);
                            d.Load();
                            Console.WriteLine("Item deleted: " + d.Subject);
                            break;

                        case EventType.Moved:
                            Item d1 = Item.Bind(service, itemEvent.ItemId);
                            d1.Load();
                            Console.WriteLine("Item deleted: " + d1.Subject);
                            break;
                        case EventType.Modified:
                            Item tem = Item.Bind(service, itemEvent.ItemId);
                            tem.Load();
                            Console.WriteLine("Item Modified: " + tem.Subject);
                            // Console.WriteLine("Item Id:" + tem.Id);
                            break;
                    }
                }

            }
            else
            {

                Console.WriteLine("No Events");
            }
            NoEvents:
            Console.WriteLine("Now waiting for pull notifications on the following folder");
            Console.WriteLine("FolderId: {0}", rootSyncFolder);
            Console.WriteLine("--------");


            return PullSubscription;

        }




        // Catch and display errors.
        static void OnError(object sender, SubscriptionErrorEventArgs args)
        {
            // Handle error conditions.
            Exception e = args.Exception;
            Console.WriteLine("\n-------------Error ---" + e.Message + "-------------");
        }

    }
}



Thursday, July 7, 2016

Ajax form validation on POST with uploadfiles

Using Ajax to submit form data including files


$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form    = $(e.target),
                formData = new FormData(),
                params   = $form.serializeArray(),
                files    = $form.find('[name="uploadedFiles"]')[0].files;

            $.each(files, function(i, file) {
                // Prefix the name of uploaded files with "uploadedFiles-"
                // Of course, you can change it to any string
                formData.append('uploadedFiles-' + i, file);
            });

            $.each(params, function(i, val) {
                formData.append(val.name, val.value);
            });

            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(result) {
                    // Process the result ...
                }
            });
        });
});

Please pay attention on contentType and processData options of the jQuery's ajax() method:

Setting contentType: false tells jQuery to not add Content-Type to the request
Setting processData: false tells jQuery to not convert our data (which is a FormData instance) to a string
On the server side, you can get the uploaded files under the names uploadedFiles-0, uploadedFiles-1, and so forth, depending how many files are chosen.

FormData are supported in modern browsers including IE 10+. You shouldn't use it if your application needs to support previous versions of IE such as IE 8, IE 9.


 To pass objects or collections as additional data in the upload event. ( async)


 A sample approach would be to stringify the C# model and then parse it to convert it to a JavaScript object.

 function upload(e) {
    var additional = '@Html.Raw(Json.Encode(Model))';
    e.data = JSON.parse(additional);
}
Then in the Controller Action you could get the model as additional parameter..
public ActionResult Save(IEnumerable<HttpPostedFileBase> files, ModelType additional)

{ }

Saturday, January 30, 2016

Search Latitude and Longitude of Places using Google Api

Place of Birth:

Latitude:

Longitude:

Nazhigai to Time Convertor

 1 nazhigai= (24*60 = 1440)seconds
 1 nazhigai = 24 minutes 
 1 nazhigai= 0.4 hours
 
 1 hour = 2.5 nazhigai
 1 hour = 150 vinazhigai
 1 hour = 9000 tharparai
 
 1 hour = 60 mintues
 1 minute = 60 seconds
 
 1 nazhigai = 60 vinazhigai
 1 vinaizhigai = 60 tharparai
 
 1 day = 24 hours = 60 nazhigai


Nazhigai:    Vinadi:   Tharparai:  

Hours:   Minutes:   Seconds:  

Monday, January 18, 2016

Name Numerology Calculator

Name:



Tuesday, November 11, 2014

Customize controls in javascript - example- A Textbox


/********************************************
** Javascript Functions of iTextBox Control
********************************************/

// Class iTextBox
function iTextBox(sId) {
    //ID passed thru Constructor
    this.ID = sId;

    //Initialize Control
    this.Initialize = function() {
        var objCtl = this.HTMLControl();
        //SetVisible
        if(objCtl.Visible.toLowerCase() == 'false')
            this.SetVisible(false);
        else
            this.SetVisible(true);
        //
        if(this.GetText().indexOf('.') != -1){
            this.SetText(this.GetText());
        }
        this.SetViewState();
    }
   
    this.SelectStart = function(){
        event.cancelBubble = true;
        return true;
    }

    this.IsVisible = function() {
        var objCtl = this.HTMLControl();
        if (objCtl == null) {
            return false;
        } else {
            if (objCtl.style.display == "none") {
                return false;
            } else {
                return true;
            }
        }
    }

    this.SetVisible = function(bFlag) {
        var objCtl = this.HTMLControl();

        if (bFlag){
            objCtl.Visible = 'true';
            objCtl.style.display = "block";
        } else {
            objCtl.Visible = 'false';
            objCtl.style.display = "none";
        }
        this.SetViewState();
    }
   
    this.IsDisplayed = function() {
        var objCtl = this.HTMLControl();
        if (objCtl == null) {
            return false;
        } else {
            if (objCtl.style.visibility == "hidden") {
                return false;
            } else {
                return true;
            }
        }
    }
   
    this.SetDisplayed = function(bFlag) {
        var objCtl = this.HTMLControl();

        if (bFlag) {
            objCtl.Displayed = 'true';
            objCtl.style.visibility = "visible";
        } else {
            objCtl.Displayed = 'false';
            objCtl.style.visibility = "hidden";
        }
        this.SetViewState();
    }

    this.IsEnabled = function() {
        var objCtl = this.HTMLControl();
        if (objCtl == null) {
            return false;
        } else {
            if (objCtl.Enabled.toLowerCase() == 'true') {
                return true;
            } else {
                return false;
            }
        }
    }

    this.SetEnabled = function(bFlag) {
       
        var objCtl = this.HTMLControl();
       
        if (bFlag)
        {
            objCtl.Enabled = 'true';
            objCtl.disabled = false;
        }
        else
        {
            objCtl.Enabled = 'false';
            objCtl.disabled = true;
        }
        //Setting ViewState
        this.SetViewState();
    }

    this.IsReadOnly = function() {
        var objCtl = this.HTMLControl();
        if (objCtl == null) {
            return false;
        } else {
            if (objCtl.TextReadOnly.toLowerCase() == 'true') {
                return true;
            } else {
                return false;
            }
        }
    }

    this.SetReadOnly = function(bFlag) {
        var objCtl = this.HTMLControl();
        if (bFlag){
            objCtl.readOnly = true;
            objCtl.TextReadOnly = 'true';
        }
        else{
            objCtl.readOnly = false;
            objCtl.TextReadOnly = 'false';
        }
        //Setting ViewState
        this.SetViewState();
    }

    this.IsMandatory = function() {
        var oCtl = this.HTMLControl();
        if (oCtl == null) {
            return false;
        } else {
            if (oCtl.Mandatory.toLowerCase() == 'true') {
                return true;
            } else {
                return false;
            }
        }
    }

    this.SetMandatory = function(bFlag) {
        var oCtl = this.HTMLControl();
        if (oCtl == null) {
            return false;
        } else {
            //Set Mandatory
            if (bFlag)
                oCtl.Mandatory = 'true';
            else
                oCtl.Mandatory = 'false';
        }
        this.SetViewState();
    }



    this.SetFocus = function() {
        var objCtl = this.HTMLControl();
        if(objCtl == null)    return false ;
        if( this.IsVisible() == true){
            objCtl.focus();
            objCtl.select();
        }
    }

    this.GetText = function() {
        return this.HTMLControl().value;
    }

    this.SetText = function(sText) {
        var oCtl = this.HTMLControl();
        if((sText.toString().indexOf('.') != -1)&& (oCtl.Precision != -1)){
            var nDiff = 1;
            var sPrec = eval(oCtl.Precision);
            for(var iIdx = 0; iIdx < sPrec; iIdx++){
                nDiff = nDiff * 10;
            }
            //
            sText = Math.floor(sText * nDiff) /nDiff;
        }
        oCtl.value = sText;
        this.SetViewState();
       
    }

    this.GetValue = function() {
        return this.GetText();
    }

    this.SetValue = function(sText) {
        this.SetText(sText);
    }

    /********************************************
    * Functions used by the iTextBox Control
    *******************************************/
    this.HTMLControl = function() {
        try {
            return document.getElementById("itextbox_Control_" + this.ID);
        } catch (e) {
            return null;
        }
    }

    this.HTMLHidden = function() {
        try {
            return document.getElementById("itextbox_Value_" + this.ID);
        } catch (e) {
            return null;
        }
    }

    this.SetViewState = function() {
        var objCtl = this.HTMLControl();
        var objText = this.HTMLHidden();
        if (objCtl.Enabled.toLowerCase() != "true") { // If DisEnabled
            objCtl.className = objCtl.css_Disabled;
        } else {
            objCtl.className = objCtl.css_Normal;
        }

        objText.value = this.IsVisible() + ";" + this.IsEnabled() + ";" + this.IsReadOnly() + ";" + this.IsMandatory() + ";" + escape(this.GetText()) + ";" + this.IsDisplayed();
    }
   
    //To set the status text
    this.Focus = function(sStatusText) {
        try
        {
            this.OnSetStatusText(sStatusText);
        }catch(e) {
        }
    }
   
    this.Change = function() {
        try{
            var objCtl = this.HTMLControl();
            this.SetViewState();
            this.OnChange(objCtl.value);
        }catch(e){
        }
    }
   
    this.KeyDown = function(){
        try{
            var objCtl = this.HTMLControl();
            if (objCtl == null)
                return false;
            if (objCtl.TextReadOnly.toLowerCase() == "true") { // If ReadOnly
                if (event.keyCode == 9 || event.keyCode == 16)
                    return true;
                else
                    event.returnValue = false;
            } else {
                this.OnKeyDown(objCtl.value);
            }
        }catch(e){
        }
    }
   
    this.KeyPress = function() {
        try{
            var objCtl = this.HTMLControl();
            if (objCtl == null)
                return false;
            if (objCtl.TextReadOnly.toLowerCase() == "true") { // If ReadOnly
                if (event.keyCode == 9 || event.keyCode == 16)
                    return true;
                else
                    event.returnValue = false;
            } else {
                this.OnKeyPress(objCtl.value);
            }
        }catch(e){
        }
    }
   
    this.KeyUp = function(){
        try{
            var objCtl = this.HTMLControl();
            if (objCtl == null)
                return false;
            if (objCtl.TextReadOnly.toLowerCase() == "true") { // If ReadOnly
                if (event.keyCode == 9 || event.keyCode == 16)
                    return true;
                else
                    event.returnValue = false;
            } else {
                this.OnKeyUp(objCtl.value);
            }
        }catch(e){
        }
    }
    
    //SetStatusText Event Handler
    this.OnSetStatusText = function(sText) {
    }
   
    // KeyDown Event Handler
    this.OnKeyDown = function(sText){
    }
   
    //KeyPress Event Handler
    this.OnKeyPress = function(sText) {
    }
   
    // KeyUp Event Handler
    this.OnKeyUp = function(sText){
    }
   
    //Change Event Handler
    this.OnChange = function(sText) {
    }
}
/********************************************/