public CCConnection SaveSubscription(CCConnection SubscObj)
 {
     if (SubscObj.ConnectionID == 0)
     {
         context.CCSubscriptions.Add(SubscObj);
         context.SaveChanges();
     }
     else
     {
         CCConnection dbEntry = context.CCSubscriptions.Find(SubscObj.ConnectionID);
         if (dbEntry != null)
         {
             dbEntry.AllowAdditions = dbEntry.AllowAdditions;
             dbEntry.IgnoreExisting = SubscObj.IgnoreExisting;
             dbEntry.CategoryFilterUsed = SubscObj.CategoryFilterUsed;
             dbEntry.CopyPhotos = SubscObj.CopyPhotos;
             dbEntry.TurnOffReminders = SubscObj.TurnOffReminders;
             dbEntry.CategoryFilterValues = SubscObj.CategoryFilterValues;
             dbEntry.SyncDirection = SubscObj.SyncDirection;
             context.SaveChanges();
         }
     }
     return SubscObj;
 }
        public ActionResult AddCrimeDiary(ExLogOnViewModel model, bool hosted = false)
        {
            Account accountObj = (Account)Session["account"];
            DateTime? d = null;
            var folderID = ((CCFolder)Session["folderDetail"]).FolderID;
            var folderNmae = ((CCFolder)Session["folderDetail"]).Name;
            string constring = string.Empty;
            var hostUrl = System.Web.HttpContext.Current.Request.Url.Host;
            if (hostUrl == "secure.corporate-contacts.com") { constring = ConfigurationManager.ConnectionStrings["TuckersConnectionDB"].ConnectionString; }
            else if (hostUrl == "staging.corporate-contacts.com") { constring = ConfigurationManager.ConnectionStrings["TuckersConnectionDB"].ConnectionString; }
            else { constring = ConfigurationManager.ConnectionStrings["TuckersConnectionTestDB"].ConnectionString; }

            CCConnection objConnection = new CCConnection();
            objConnection = model.Connection;
            objConnection.Type = "CrimeDiary";
            objConnection.FolderID = folderID;
            objConnection.AllowAdditions = false;
            objConnection.IgnoreExisting = false;
            objConnection.CategoryFilterUsed = false;
            objConnection.CopyPhotos = false;
            objConnection.TurnOffReminders = false;
            objConnection.CredentialsID = 11111;
            objConnection.Owner = "owner";
            objConnection.IsRunning = false;
            objConnection.LastSyncTime = "1900-01-01 00:00";
            objConnection.Frequency = 1440;
            objConnection.FolderName = folderNmae;
            objConnection.SourceID = constring;
            objConnection.AccessType = 0;
            objConnection.SecondaryAccount = "";
            objConnection.AccountGUID = accountObj.AccountGUID;

            if (ModelState.IsValid)
            {
                var resp = CCConnectinRepository.SaveSubscription(objConnection);
                return RedirectToAction("ViewConnections", "Folder", new { id = folderID });
            }
            else
            {
                return View(model);
            }
        }
        public ActionResult SelectFolderoptionss(SelectFolderViewModel model)
        {
            TempData["SelectedMenu"] = "Manage";
            TempData["SelectedSubMenu"] = "ManageFolders";
            Account accountObj = (Account)Session["account"];
            int type = 1;
            CCFolder folderDetails = null;
            folderDetails = CCFolderRepository.FolderDetails(model.PrimarySourceId);
            if (folderDetails != null) { type = folderDetails.Type; }
            else { type = 1; }

            User userObj = (User)Session["user"];

            var connection = new CorporateContacts.Domain.Entities.CCConnection();
            connection.FolderID = model.PrimarySourceId;
            connection.FolderName = model.SelectedFolderName;
            connection.Owner = model.SelectedFolderOwnerInfo;
            if (type == 1) { connection.Type = "Contact"; }
            else { connection.Type = "Calendar"; }
            connection.CredentialsID = model.CredentialID;
            connection.AllowAdditions = false;
            connection.IgnoreExisting = model.IgnoreExisting;
            connection.SyncDirection = model.SyncDirection;
            connection.CategoryFilterUsed = model.CategoryFilterUsed;
            connection.CopyPhotos = model.CopyPhotos;
            connection.TurnOffReminders = model.TurnOffReminders;
            connection.SourceID = model.SelectedFolderId;
            connection.Frequency = 1440;
            connection.IsRunning = false;
            connection.IsPaused = false;
            connection.SecondaryAccount = Session["secondaryAccount"] as string;
            string accessTypes = string.Empty;
            if (Session["accessType"] != null) { accessTypes = Session["accessType"].ToString(); }
            if (string.IsNullOrEmpty(accessTypes)) { connection.AccessType = 0; }
            else { connection.AccessType = Int32.Parse(accessTypes); }
            string format = "yyyy-MM-dd HH:mm";
            connection.LastSyncTime = ((DateTime)(System.Data.SqlTypes.SqlDateTime.MinValue)).ToString(format);
            if (model.CategoryFilterUsed == false) { connection.CategoryFilterValues = string.Empty; }
            else { connection.CategoryFilterValues = model.CategoryFilterValues; }
            if (model.TagAllSubject == true) { connection.SubjectTag = model.SubjectTag; }
            else { connection.SubjectTag = string.Empty; }
            connection.tagSubject = model.TagAllSubject;
            connection.AccountGUID = accountObj.AccountGUID;
            connection = CCConnectinRepository.SaveSubscription(connection);

            if (connection != null)
            {
                var foldertag = new CorporateContacts.Domain.Entities.CCConnection();
                var tagname = connection.FolderName + "[" + connection.ConnectionID + "]";
                foldertag.Tag = tagname;
                foldertag.ConnectionID = connection.ConnectionID;

                CCConnectinRepository.SaveSubscriptionTag(foldertag);
            }

            var res = CCFieldMappingsRepository.SaveAllMappingFields(connection.FolderID, connection.ConnectionID, accountObj.AccountGUID);

            LimitationsViewModel limitationsObj = (LimitationsViewModel)Session["limitations"];
            HelperFunctions HF = new HelperFunctions();
            limitationsObj = HF.updateAccountLimitations(accountObj);
            Session["limitations"] = limitationsObj;

            return RedirectToAction("ViewConnections", "Folder", new { id = connection.FolderID });
        }
        public ActionResult ChangeConnectionToggleButtons(long ConnectionID, string chkbox)
        {
            CCConnection connObj = new CCConnection();
            connObj.ConnectionID = ConnectionID;
            connObj = CCConnectionRepository.CCSubscriptions.Where(conn => conn.ConnectionID == connObj.ConnectionID).FirstOrDefault();

            if (chkbox == "RestartTimer")
            {
                connObj.LastSyncTime = "1753-01-01 00:00";
            }
            else
            {
                if (chkbox == "AllowAdditions")
                {
                    if (connObj.AllowAdditions == true)
                        connObj.AllowAdditions = false;
                    else
                        connObj.AllowAdditions = true;
                }

                if (chkbox == "IgnoreExisting")
                {
                    if (connObj.IgnoreExisting == true)
                        connObj.IgnoreExisting = false;
                    else
                        connObj.IgnoreExisting = true;
                }

                if (chkbox == "CategoryFilterUsed")
                {
                    if (connObj.CategoryFilterUsed == true)
                        connObj.CategoryFilterUsed = false;
                    else
                        connObj.CategoryFilterUsed = true;
                }

                if (chkbox == "CopyPhotos")
                {
                    if (connObj.CopyPhotos == true)
                        connObj.CopyPhotos = false;
                    else
                        connObj.CopyPhotos = true;
                }

                if (chkbox == "TurnOffReminders")
                {
                    if (connObj.TurnOffReminders == true)
                        connObj.TurnOffReminders = false;
                    else
                        connObj.TurnOffReminders = true;
                }

                if (chkbox == "tagSubject")
                {
                    if (connObj.tagSubject == true)
                        connObj.tagSubject = false;
                    else
                        connObj.tagSubject = true;
                }
                if (chkbox == "IsRunning")
                {
                    if (connObj.IsRunning == true)
                        connObj.IsRunning = false;
                    else
                        connObj.IsRunning = true;
                }
                if (chkbox == "IsPaused")
                {
                    if (connObj.IsPaused == true)
                        connObj.IsPaused = false;
                    else
                        connObj.IsPaused = true;
                }
            }

            bool update = CCConnectionRepository.UpdateConnectionBooleanToggles(connObj);

            Account AccObj = CCAccRepository.Accounts.Where(acc => acc.AccountGUID == connObj.AccountGUID).FirstOrDefault();

            return RedirectToAction("ViewConnectionDetails", "CorporateContactsAdmin", new { ConnectionID = connObj.ConnectionID, AccID = AccObj.ID});
        }
 public CCConnection SaveSubscriptionTag(CCConnection SubscObj)
 {
     CCConnection dbEntry = context.CCSubscriptions.Find(SubscObj.ConnectionID);
     if (dbEntry != null)
     {
         dbEntry.Tag = SubscObj.Tag;
         context.SaveChanges();
     }
     return SubscObj;
 }
        public bool UpdateSubscription(CCConnection SubscObj)
        {
            CCConnection dbEntry = context.CCSubscriptions.Find(SubscObj.ConnectionID);
            if (dbEntry != null)
            {

                dbEntry.SubjectTag = SubscObj.SubjectTag;
                dbEntry.tagSubject = SubscObj.tagSubject;
                dbEntry.AllowAdditions = dbEntry.AllowAdditions;
                dbEntry.IgnoreExisting = SubscObj.IgnoreExisting;
                dbEntry.CategoryFilterUsed = SubscObj.CategoryFilterUsed;
                dbEntry.CopyPhotos = SubscObj.CopyPhotos;
                dbEntry.TurnOffReminders = SubscObj.TurnOffReminders;
                dbEntry.CategoryFilterValues = SubscObj.CategoryFilterValues;
                dbEntry.SyncDirection = SubscObj.SyncDirection;
                context.SaveChanges();
                return true;
            }
            return false;
        }
        public bool UpdatePauseSync(CCConnection SubscObj)
        {
            CCConnection dbEntry = context.CCSubscriptions.Find(SubscObj.ConnectionID);
            if (dbEntry != null)
            {
                if (SubscObj.IsPaused != null)
                {
                    dbEntry.IsPaused = SubscObj.IsPaused;
                }
            }
            context.SaveChanges();

            return true;
        }
        public bool UpdateConnectionBooleanToggles(CCConnection SubscObj)
        {
            CCConnection dbEntry = context.CCSubscriptions.Find(SubscObj.ConnectionID);
            if (dbEntry != null)
            {
                if (SubscObj.AllowAdditions != null)
                {
                    dbEntry.AllowAdditions = SubscObj.AllowAdditions;
                }
                if (SubscObj.IgnoreExisting != null)
                {
                    dbEntry.IgnoreExisting = SubscObj.IgnoreExisting;
                }
                if (SubscObj.CategoryFilterUsed != null)
                {
                    dbEntry.CategoryFilterUsed = SubscObj.CategoryFilterUsed;
                }
                if (SubscObj.CopyPhotos != null)
                {
                    dbEntry.CopyPhotos = SubscObj.CopyPhotos;
                }
                if (SubscObj.TurnOffReminders != null)
                {
                    dbEntry.TurnOffReminders = SubscObj.TurnOffReminders;
                }
                if (SubscObj.tagSubject != null)
                {
                    dbEntry.tagSubject = SubscObj.tagSubject;
                }
                if (SubscObj.IsRunning != null)
                {
                    dbEntry.IsRunning = SubscObj.IsRunning;
                }
                if (SubscObj.IsPaused != null)
                {
                    dbEntry.IsPaused = SubscObj.IsPaused;
                }

                if (SubscObj.LastSyncTime != null)
                {
                    dbEntry.LastSyncTime = SubscObj.LastSyncTime;
                }
                context.SaveChanges();
            }
            return true;
        }
        public ConnectionImportListSummaryModel ImportConnections(long fid, string aguid, string path, string fileExtension, long credID, string accessMethod, string syncDirection, long maxConnectionImportCount)
        {
            if (inputdatas == null)
                inputdatas = new DataInputHelper(path, fileExtension);

            bool _readheader = true;
            var _availablevalue = new List<Tuple<string, string>>();
            var colCount = 0;
            var rowCount = 0;
            ConnectionImportListSummaryModel connSummary = new ConnectionImportListSummaryModel();

            DataTable valus = inputdatas.GetImportExcel();

            var totalRowCount = (valus.Rows.Count) - 1;

            if (totalRowCount <= maxConnectionImportCount)
            {
                foreach (DataRow row in valus.Rows)
                {

                    CCConnection ConnectionObj = new CCConnection();

                    foreach (DataColumn col in valus.Columns)
                    {
                        string _colname = row[col].ToString();
                        if (_readheader) // run when it header
                        {
                            continue;
                        }
                        else
                        {
                            if (colCount == 0)
                            {
                                ConnectionObj.SecondaryAccount = _colname;
                                colCount++;
                            }
                            else
                            {
                                if (_colname != "")
                                {
                                    ConnectionObj.CategoryFilterUsed = true;
                                    ConnectionObj.CategoryFilterValues = _colname;
                                }
                            }
                        }
                    }
                    colCount = 0;

                    if (rowCount != 0)
                    {
                        ConnectionList.Add(ConnectionObj);
                    }

                    rowCount++;
                    _readheader = false;
                }

                NumberOfConnections = ConnectionList.Count;
                ExchangeService srv = null;
                Credential creds = CCCredentialRepository.Credentials.Where(cre => cre.ID == credID).FirstOrDefault();

                string depassword = Encryption.DecryptStringAES(creds.Password, rand);
                if (creds.IsHostedExchange)
                {
                    srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    if (creds.EmailAddress != null) { srv.Credentials = new WebCredentials(creds.EmailAddress, depassword); }
                    else { srv.Credentials = new WebCredentials(creds.UserName, depassword); }
                    srv.Url = new Uri(creds.URL);
                }
                else
                {
                    if (creds.ServerVersion == "2007SP1") srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    else if (creds.ServerVersion == "2010") srv = new ExchangeService(ExchangeVersion.Exchange2010);
                    else if (creds.ServerVersion == "2010SP1") srv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                    else if (creds.ServerVersion == "Exchange2010_SP1") srv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                    else if (creds.ServerVersion == "Exchange2010_SP2") srv = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                    else srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    if (creds.Domain != null) { srv.Credentials = new WebCredentials(creds.UserName, depassword, creds.Domain); }
                    else if (creds.UserName != null) { srv.Credentials = new WebCredentials(creds.UserName, depassword); }
                    else { srv.Credentials = new WebCredentials(creds.EmailAddress, depassword); }
                    srv.Url = new Uri(creds.URL);
                }

                int type = CCFolderRepo.CCFolders.FirstOrDefault(f => f.FolderID == fid).Type;
                long primarySourceID = 0;
                long credentialsID = 0;
                try { primarySourceID = Convert.ToInt64(fid); }
                catch { }

                try { credentialsID = Convert.ToInt64(creds.ID); }
                catch { }

                int successfulConnections = 0;

                foreach (var conToCreate in ConnectionList)
                {
                    bool addTopFolder = false;
                    ExchangeService ex = srv;
                    Folder fold = null;
                    Folder publicFolder = null;

                    //CorporateContacts.WebUI.Controllers.FolderController.conectionBeingAddedEmail = conToCreate.SecondaryAccount;

                    //System.Web.HttpContext.Current.Application["Name"] = "Value";

                    try
                    {
                        if (accessMethod == "1")
                        {
                            ex.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, conToCreate.SecondaryAccount);
                            if (type == 1)
                            {
                                fold = Folder.Bind(ex, new FolderId(WellKnownFolderName.Contacts, conToCreate.SecondaryAccount));
                            }
                            else
                            {
                                fold = Folder.Bind(ex, new FolderId(WellKnownFolderName.Calendar, conToCreate.SecondaryAccount));
                            }

                            addTopFolder = true;
                        }
                        else
                        {
                            //ex.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, conToCreate.SecondaryAccount);
                            if (type == 1)
                            {
                                fold = Folder.Bind(ex, new FolderId(WellKnownFolderName.Contacts, conToCreate.SecondaryAccount));
                            }
                            else
                            {
                                fold = Folder.Bind(ex, new FolderId(WellKnownFolderName.Calendar, conToCreate.SecondaryAccount));
                            }

                            addTopFolder = true;
                        }

                        //var f = Folder.Bind(ex, WellKnownFolderName.MsgFolderRoot);
                        TreeViewFolder mailBox = new TreeViewFolder();
                        TreeViewFolder publicBox = new TreeViewFolder();
                        string FolderSourceID = "";

                        if (fold != null)
                        {
                            var tree = LoadSubFolders(fold, new TreeViewFolder(), addTopFolder, fid);

                            mailBox.Name = "*Mail Folders";
                            mailBox.FolderClass = "All";

                            foreach (var it in tree.ChildFolders)
                            {
                                FolderSourceID = it.Id;
                                break;
                                //mailBox.ChildFolders.Add(it);
                            }

                        }

                        if (publicFolder != null)
                        {
                            var treepublic = LoadSubFolders(publicFolder, new TreeViewFolder(), addTopFolder, fid);

                            publicBox.Name = "*Public Folders";
                            publicBox.FolderClass = "All";

                            foreach (var it in treepublic.ChildFolders)
                            {
                                FolderSourceID = it.Id;
                                break;
                                //publicBox.ChildFolders.Add(it);
                            }

                        }

                        //Save the Connection
                        var connection = new CorporateContacts.Domain.Entities.CCConnection();
                        connection.FolderID = primarySourceID;
                        if (type == 1) { connection.FolderName = "Contacts"; }
                        else { connection.FolderName = "Calendar"; }

                        connection.Owner = creds.EmailAddress;

                        if (type == 1) { connection.Type = "Contact"; }
                        else { connection.Type = "Calendar"; }

                        connection.CredentialsID = credentialsID;
                        connection.AllowAdditions = false;
                        connection.IgnoreExisting = true;
                        connection.SyncDirection = syncDirection;
                        connection.CategoryFilterUsed = conToCreate.CategoryFilterUsed;

                        if(connection.Type == "Contact")
                            connection.CopyPhotos = true;
                        else
                            connection.CopyPhotos = false;

                        if (connection.Type == "Calendar")
                            connection.TurnOffReminders = true;
                        else
                            connection.TurnOffReminders = false;

                        connection.SourceID = FolderSourceID;
                        connection.Frequency = 1440;
                        connection.IsRunning = false;
                        connection.IsPaused = false;
                        connection.SecondaryAccount = conToCreate.SecondaryAccount;

                        if (accessMethod == "1")
                        {
                            connection.AccessType = 1;
                        }
                        else
                        {
                            connection.AccessType = 2;
                        }
                        string format = "yyyy-MM-dd HH:mm";
                        connection.LastSyncTime = ((DateTime)(System.Data.SqlTypes.SqlDateTime.MinValue)).ToString(format);
                        connection.CategoryFilterValues = conToCreate.CategoryFilterValues;
                        connection.SubjectTag = string.Empty;
                        connection.tagSubject = false;
                        connection.AccountGUID = aguid;
                        connection = CCConnectionRepo.SaveSubscription(connection);

                        if (connection != null)
                        {
                            var foldertag = new CorporateContacts.Domain.Entities.CCConnection();
                            var tagname = connection.FolderName + "[" + connection.ConnectionID + "]";
                            foldertag.Tag = tagname;
                            foldertag.ConnectionID = connection.ConnectionID;

                            CCConnectionRepo.SaveSubscriptionTag(foldertag);
                        }

                        var res = CCFieldMappingsRepository.SaveAllMappingFields(connection.FolderID, connection.ConnectionID, aguid);
                        successfulConnections++;
                    }
                    catch (Exception e)
                    {
                        connSummary.UnsuccessfulEmailList.Add(conToCreate.SecondaryAccount);

                    }
                }
                connSummary.NoOfSuccessfullConnections = successfulConnections;
                return connSummary;
            }
            else
            {
                ConnectionImportListSummaryModel connSummaryFail = new ConnectionImportListSummaryModel();
                connSummaryFail.maxConnectionLevelReach = true;

                return connSummaryFail;
            }
        }
        public ActionResult ChangeSyncState(string ActionType, string ID, string Value)
        {
            User userObj = (User)Session["user"];
            Account accountObj = (Account)Session["account"];

            if (ModelState.IsValid && accountObj != null)
            {
                if (ActionType == "Folder")
                {
                    CCFolder folderObj = new CCFolder();
                    folderObj.FolderID = long.Parse(ID);

                    if (Value == "1")
                        folderObj.IsPaused = false;
                    else
                        folderObj.IsPaused = true;

                    bool folderUpdate = CCFolderRepository.UpdatePauseSync(folderObj);

                    //Change state of IsPaused in Connections as well..
                    var connectionListOfFolder = CCConnectionRepository.CCSubscriptions.Where(fid => fid.FolderID == folderObj.FolderID).ToList();

                    foreach (var conn in connectionListOfFolder)
                    {
                        CCConnection connectionObj = new CCConnection();
                        connectionObj.ConnectionID = conn.ConnectionID;

                        if (Value == "1")
                            connectionObj.IsPaused = false;
                        else
                            connectionObj.IsPaused = true;

                        bool connectionUpdate = CCConnectionRepository.UpdatePauseSync(connectionObj);
                    }
                }
                else if (ActionType == "Connection")
                {
                    CCConnection connectionObj = new CCConnection();
                    connectionObj.ConnectionID = long.Parse(ID);

                    if (Value == "1")
                        connectionObj.IsPaused = false;
                    else
                        connectionObj.IsPaused = true;

                    bool connectionUpdate = CCConnectionRepository.UpdatePauseSync(connectionObj);
                }
            }
            return RedirectToAction("Index", "Admin");
        }