Example #1
0
 /// <summary>
 /// Static main method
 /// </summary>
 /// <param name="args">Command line argument</param>
 public static void Main(string[] args)
 {
     if (2 <= args.Length && !ExcelOperations.IsNullOrEmptyCredential(args[0], args[1]))
     {
         Dictionary <string, string> configVal = ExcelOperations.ReadFromExcel(filePath, ConfigurationManager.AppSettings["configSheetName"]);
         string username = args[0].Trim();
         string password = args[1].Trim();
         try
         {
             string targetSite = configVal["CatalogSiteURL"];
             using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(targetSite, username, password))
             {
                 CreateUpdateProvisionMatterListPermissions(clientContext, configVal);
             }
         }
         catch (Exception exception)
         {
             ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
         }
     }
     else
     {
         ErrorMessage.ShowMessage("Please enter username and password", ErrorMessage.MessageType.Error);
     }
 }
        public string LoadBankPOSFile(byte[] formData)
        {
            using (IDAL dal = this.DAL)
            {
                dal.BeginTransaction();
                try
                {
                    _logger.Debug($"Pos Transfer file read started : {DateTime.Now.ToLongTimeString()}");
                    ExcelOperations exOp = new ExcelOperations(dal);

                    string result = exOp.ReadExceltoDataTable(formData, "Pos Transfer", 1); // filetype 1: xlsx
                    if (result.Length == 0)
                    {
                        DataTable dt = exOp.ExcelTable;
                        result = insertDataTabletoPOSTable(dt, dal, 1);
                    }
                    if (result.Length == 0)
                    {
                        dal.CommitTransaction();
                    }
                    else
                    {
                        dal.RollbackTransaction();
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    dal.RollbackTransaction();
                    throw ex;
                }
            }
        }
Example #3
0
        /// <summary>
        /// 获得模版
        /// </summary>
        /// <returns></returns>
        public void GetTemp()
        {
            String     fileName = Server.MapPath("/File/expBank.xls");
            FileStream stream   = System.IO.File.OpenRead(fileName);
            IWorkbook  excel    = ExcelOperations.GetIWorkbook(stream, ExcelType.xls);
            ISheet     sheet    = excel.GetSheet("Life");

            List <Diction> dictions = new BLL.LifeMan.BLDiction().Select(new HashTableExp("ParentId", "1000200000"), String.Empty);

            for (int i = 0; i < dictions.Count; i++)
            {
                sheet.CreateRow(i + 2).CreateCell(8).SetCellValue(dictions[i].Name);
            }

            dictions = new BLL.LifeMan.BLDiction().Select(new HashTableExp("ParentId", "1000100000"), String.Empty);
            for (int i = 0; i < dictions.Count; i++)
            {
                sheet.CreateRow(i + 5).CreateCell(6).SetCellValue(dictions[i].Name);
            }

            sheet = null;

            MemoryStream ms = new MemoryStream();

            excel.Write(ms);
            Response.AppendHeader("Content-Disposition", "attachment;filename=银行信息模版.xls");
            Response.BinaryWrite(ms.ToArray());
            Response.End();
            ms.Close();
            ms = null;
        }
Example #4
0
 /// <summary>
 /// Read configuration values from Excel and create term store hierarchy
 /// </summary>
 /// <param name="listval">Configuration values from configuration Excel</param>
 /// <param name="action">Flag to create or delete hierarchy</param>
 public static void ReadConfigExcel(Dictionary <string, string> listval, bool action)
 {
     try
     {
         string filePath        = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
         string termSheetName   = ConfigurationManager.AppSettings["termconfig"];
         string clientSheetName = ConfigurationManager.AppSettings["clientconfig"];
         if (System.IO.File.Exists(filePath))
         {
             Collection <Collection <string> > termSheetValues   = ExcelOperations.ReadSheet(filePath, termSheetName);
             Collection <Collection <string> > clientSheetValues = ExcelOperations.ReadSheet(filePath, clientSheetName);
             List <DataStorage> termList   = ReadTermData(termSheetValues, "Practice_Group").ToList();
             List <DataStorage> clientList = ReadTermData(clientSheetValues, "Client").ToList();
             if (action)
             {
                 CreateTermStructure(listval, termList);
                 CreateClientStructure(listval, clientList, action);
             }
             else
             {
                 CreateClientStructure(listval, clientList, action);
             }
         }
         else
         {
             ErrorLogger.LogErrorToTextFile(errorFilePath, "Couldn't find file: " + filePath);
         }
     }
     catch (Exception exception)
     {
         ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
     }
 }
Example #5
0
        public static void Main(string[] args)
        {
            if (2 <= args.Length)
            {
                string username = args[1], password = args[2];
                bool   action = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture); // Flag to Create or Delete Term store Hierarchy
                if (!ExcelOperations.IsNullOrEmptyCredential(username, password))
                {
                    Console.WriteLine("Reading inputs from Excel...");
                    string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
                    string sheetName = ConfigurationManager.AppSettings["sheetname"];

                    Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
                    listval.Add("Username", username);
                    listval.Add("Password", password);
                    if (args.Length != 0 && !string.IsNullOrWhiteSpace(args[0]))
                    {
                        ReadConfigExcel(listval, action);
                    }
                }
                else
                {
                    ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Invalid Credentials");
                }
            }
            else
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Insufficient Parameters");
            }
        }
Example #6
0
        private void bKT_Click(object sender, EventArgs e)
        {
            var excPkg = ExcelOperations.GetExcelPackage(SelectedOrder.selectedOrder.modelId);// currentOrder.modelId);

            if (excPkg != null)
            {
                string additionalComment = "";// lProdWerehouseStock.Text != "" ? $"Wyrób znajduje się na regale: {lProdWerehouseStock.Text}" : "";
                if (ProductionStock.CurrentStock.Count > 0)
                {
                    additionalComment = $"Wyrób znajduje się na regale: {string.Join(", ", ProductionStock.CurrentStock)}";
                }

                string tempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), ExcelOperations.ExcelParameters.tempFileName);
                for (int i = 0; i < 20; i++) //try 20 filenames for tempFile
                {
                    tempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"{i}_{ExcelOperations.ExcelParameters.tempFileName}");
                    if (!ExcelOperations.IsFileLocked(new FileInfo(tempFile)))
                    {
                        break;
                    }
                    if (i == 14)
                    {
                        MessageBox.Show("Nie można uzystać dostępu do programu Excel. Zamknij wszystkie okna Excel i spróbuj ponownie." + Environment.NewLine + "W razie dalszych problemów uruchom ponownie komputer");
                        return;
                    }
                }

                ExcelOperations.FillOutExcelData(ref excPkg, false, additionalComment);
                ExcelOperations.SaveToExcel(excPkg, tempFile);
                Process.Start(tempFile);
            }
        }
        /// <summary>
        /// Function to create Site columns in content type hub
        /// </summary>
        /// <param name="revert">Flag to create or remove site columns</param>
        /// <param name="login">Username for authentication</param>
        /// <param name="password">Password for authentication</param>
        internal static void AddSiteColumns(bool revert, string login, string password)
        {
            string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
            string sheetName = ConfigurationManager.AppSettings["sheetname"];

            // Read from Excel
            Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);

            if (listval.Count != 0)
            {
                string targetSite        = listval["ContentTypeHubURL"];                                                                     // Get the URL of site collection
                string contentType       = ConfigurationManager.AppSettings["ContentTypeValue"];                                             // Get Content Type DMS from Excel
                string contentTypegroup  = ConfigurationManager.AppSettings["ContentTypeGroupValue"];                                        // Get Group of Content Type
                bool   isDeployedOnAzure = Convert.ToBoolean(listval["IsDeployedOnAzure"].ToUpperInvariant(), CultureInfo.InvariantCulture); // Get Is Deployed on Azure parameter

                try
                {
                    string        siteColNames = GetConfigDataFromResource("SiteColumn_Config", "SiteColumnNames");
                    List <string> siteColumns  = siteColNames.Split(new char[] { ',' }).ToList();

                    using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(targetSite, login, password, isDeployedOnAzure))
                    {
                        try
                        {
                            if (revert)
                            {
                                // Revert the creation of Site Columns
                                RevertSiteColumns(clientContext, siteColumns, contentType, contentTypegroup);
                            }
                            else
                            {
                                bool nextStep = CreateSiteColumn(clientContext, siteColumns, contentTypegroup);
                                if (nextStep)
                                {
                                    bool typeCreated = CreateContentType(clientContext, siteColumns, contentType, contentTypegroup);
                                    if (typeCreated)
                                    {
                                        Console.WriteLine(GetConfigDataFromResource("SiteColumn_Config", "MsgContentTypeCreated"));
                                    }
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                        }
                    }
                }
                catch (Exception exception)
                {
                    ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                }
            }
            else
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: No inputs from Excel file...");
            }
        }
        public string ZiraatLoadBankPOSFile(byte[] formData)
        {
            using (IDAL dal = this.DAL)
            {
                dal.BeginTransaction();
                try
                {
                    _logger.Debug($"Ziraat Pos Transfer file read started : {DateTime.Now.ToLongTimeString()}");
                    ExcelOperations exOp           = new ExcelOperations(dal);
                    long            eventId        = _parameterReader.ReadEventId("System");
                    long            organizationId = OTApplication.Context.Organization.Id;
                    string          result         = exOp.ReadExceltoDataTable(formData, "Ziraat POS", 2); // filetype 2: csv
                    if (result.Length == 0)
                    {
                        DataTable dt = exOp.ExcelTable;
                        dt.Columns.Add("ADET", typeof(decimal));
                        dt.Columns.Add("BORCTUTARI", typeof(decimal));
                        dt.Columns.Add("KOMISYON", typeof(decimal));

                        var newDt = dt.AsEnumerable()
                                    .GroupBy(r => new { TERMID = r.Field <string>("TERMID"), UYENO = r.Field <string>("UYENO"), BLOKETARIHI = r.Field <DateTime>("BLOKETARIHI"), BLOKEVALORU = r.Field <DateTime>("BLOKEVALORU") })
                                    .Select(g =>
                        {
                            var row = dt.NewRow();


                            row["UYENO"]        = g.Key.UYENO;
                            row["TERMID"]       = g.Key.TERMID.TrimStart(new Char[] { '0' });
                            row["BLOKETARIHI"]  = g.Key.BLOKETARIHI;
                            row["BLOKEVALORU"]  = g.Key.BLOKEVALORU;
                            row["ALACAKTUTARI"] = g.Sum(r => r.Field <decimal>("ALACAKTUTARI"));
                            row["ADET"]         = g.Count();
                            row["BORCTUTARI"]   = 0;
                            row["KOMISYON"]     = 0;

                            return(row);
                        }).CopyToDataTable();

                        result = insertDataTabletoPOSTable(newDt, dal, 4);
                    }
                    if (result.Length == 0)
                    {
                        dal.CommitTransaction();
                    }
                    else
                    {
                        dal.RollbackTransaction();
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    dal.RollbackTransaction();
                    throw ex;
                }
            }
        }
        /// <summary>
        /// Main method - Start of the program
        /// </summary>
        /// <param name="args">Input from console</param>
        public static void Main(string[] args)
        {
            bool   revert = false;
            string login, password;

            if (null != args && 2 <= args.Length)
            {
                revert   = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture);
                login    = args[1];
                password = args[2];

                if (!ExcelOperations.IsNullOrEmptyCredential(login, password))
                {
                    Console.WriteLine("Reading inputs from Excel...");
                    string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + ConfigurationManager.AppSettings["filename"];
                    string sheetName = ConfigurationManager.AppSettings["sheetname"];
                    Collection <Collection <string> > groupSheetValues = ExcelOperations.ReadSheet(filePath, ConfigurationManager.AppSettings["groupsheetname"]);
                    string groupName     = Convert.ToString(groupSheetValues[1][0], CultureInfo.InvariantCulture);
                    string errorFilePath = Directory.GetParent(Directory.GetCurrentDirectory()) + ConfigurationManager.AppSettings["errorLogFile"];
                    Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
                    if (listval.Count() > 0)
                    {
                        string targetSite        = listval["CatalogSiteURL"];                                                                        // Get the URL of site collection
                        bool   isDeployedOnAzure = Convert.ToBoolean(listval["IsDeployedOnAzure"].ToUpperInvariant(), CultureInfo.InvariantCulture); // Get Is Deployed on Azure parameter
                        using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(targetSite, login, password, isDeployedOnAzure))
                        {
                            int listCount = 0;
                            try
                            {
                                listCount = Convert.ToInt32(ConfigurationManager.AppSettings["ListCount"], CultureInfo.InvariantCulture); // Get the total number of lists to be created
                                RevertCreatedList(clientContext, listCount, errorFilePath);
                                RemovePermissionLevelIfExists(clientContext, ConfigurationManager.AppSettings["MatterCenterContributePermission"]);
                                if (!revert)
                                {
                                    CreateSharePointList(clientContext, listCount, groupName); // Create SharePoint List
                                    AddRoleDetails(clientContext);
                                }
                            }
                            catch (Exception exception)
                            {
                                RevertCreatedList(clientContext, listCount, errorFilePath);
                                RemovePermissionLevelIfExists(clientContext, ConfigurationManager.AppSettings["MatterCenterContributePermission"]);
                                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: No inputs found");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid Credentials.");
                }
            }
        }
Example #10
0
        /// <summary>
        /// Program Entry Point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            try
            {
                if (5 <= args.Length)
                {
                    bool uploadAssets = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture);
                    if (!ExcelOperations.IsNullOrEmptyCredential(args[1], args[2]))  // Validate Username and Password and azure website url
                    {
                        Console.WriteLine("Reading inputs from Excel...");
                        string parentPath = Convert.ToString(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, CultureInfo.InvariantCulture);
                        Console.WriteLine(parentPath);
                        string filePath = parentPath + "\\" + ConfigurationManager.AppSettings["filename"];
                        Console.WriteLine(filePath);
                        string sheetName = ConfigurationManager.AppSettings["configsheetname"];
                        Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
                        string login                    = args[1]; // Get the user name
                        string password                 = args[2]; // Get the password
                        string azureWebsiteUrl          = args[3];
                        string appInsightsId            = args[4];
                        string catalogURL               = listval["CatalogSiteURL"];
                        string matterCenterAssetsFolder = ConfigurationManager.AppSettings["AssetsFolder"];
                        parentPath = Convert.ToString(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, CultureInfo.InvariantCulture);

                        using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(catalogURL, login, password))
                        {
                            List siteAssets;
                            ListItemCollection matterCenterFolder;
                            FolderCollection   listFolders;
                            matterCenterFolder = CheckFolderExists(matterCenterAssetsFolder, clientContext, out siteAssets, out matterCenterFolder, out listFolders);

                            if (0 < matterCenterFolder.Count)
                            {
                                Console.WriteLine("\n " + matterCenterAssetsFolder + " already present... Deleting...");
                                matterCenterFolder[0].DeleteObject();
                                clientContext.ExecuteQuery();
                                Console.WriteLine("Successfully deleted " + matterCenterAssetsFolder + " from SharePoint.");
                            }

                            if (uploadAssets)
                            {
                                UploadFilesToFolder(matterCenterAssetsFolder, clientContext, siteAssets,
                                                    listFolders, listval, azureWebsiteUrl, appInsightsId);
                            }
                        }
                    }
                }
                else
                {
                    ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Insufficient Parameters");
                }
            }
            catch (Exception exception)
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
            }
        }
Example #11
0
        public void OpenWorkbook()
        {
            var workbook = ExcelOperations.OpenReportWorkbook("BlankReport.xlsx");

            var worksheet = workbook.Worksheets.First();

            var range = worksheet.RangeForCell(1, 1);

            range.SetText("Hi Janice!");
        }
Example #12
0
        /// <summary>
        /// Storing Credentials For SharePoint
        /// </summary>
        /// <param name="login">Login detail</param>
        /// <param name="password">Pass word</param>
        /// <returns>Client context object</returns>
        public static ClientContext GetClientContext(string login, string password)
        {
            string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
            string sheetName = ConfigurationManager.AppSettings["sheetname"];
            // Read from Excel
            Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
            string catalogSiteURL = listval["TenantURL"];

            return(ConfigureSharePointContext.ConfigureClientContext(catalogSiteURL, login, password));
        }
        public void VerifyLoginWithAlreadyCreatedUser()
        {
            LoginPage    regNow    = new LoginPage(driver);
            HomePageTest hmpg_test = new HomePageTest();

            hmpg_test.CheckNavigationToLoginPage();

            //string FileName = Environment.CurrentDirectory.ToString() + "\\ConfigFile\\TestDataFile.xlsx";
            ExcelOperations.PopulateInCollection(FileName, "LoginUser");
            //Thread.Sleep(1000);
            regNow.Login(ExcelOperations.ReadData(1, "Email"), ExcelOperations.ReadData(1, "Password"));
        }
Example #14
0
 /// <summary>
 /// Main method
 /// </summary>
 /// <param name="args">Command line arguments</param>
 public static void Main(string[] args)
 {
     if (null != args && 2 <= args.Length && !ExcelOperations.IsNullOrEmptyCredential(args[1], args[2]))
     {
         bool revert = Convert.ToBoolean(args[0].ToUpperInvariant(), CultureInfo.InvariantCulture);
         Console.WriteLine("Reading inputs from Excel...");
         AddSiteColumns(revert, args[1], args[2]);
     }
     else
     {
         ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Insufficient Parameters");
     }
 }
Example #15
0
        /// <summary>
        /// Main Method to initiate the execution
        /// </summary>
        /// <param name="args">Command line argument</param>
        public static void Main(string[] args)
        {
            try
            {
                if (null != args && 2 <= args.Length)
                {
                    bool createData = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture);
                    if (!ExcelOperations.IsNullOrEmptyCredential(args[1], args[2]))
                    {
                        //// Read Configuration sheet and Sample data sheet from Excel
                        string filePath        = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
                        string sheetName       = ConfigurationManager.AppSettings["sheetname"];
                        string configSheetName = ConfigurationManager.AppSettings["configsheetname"];
                        Dictionary <string, string> configVal = ExcelOperations.ReadFromExcel(filePath, configSheetName);
                        configVal.Add("Username", args[1].Trim());
                        configVal.Add("Password", args[2].Trim());
                        Collection <Collection <string> > dataValue = ExcelOperations.ReadSheet(filePath, sheetName);
                        List <DataStorage> matterDetails            = MatterProvisionHelper.FetchMatterData(dataValue);
                        ClientTermSets     clientDetails            = TermStoreOperations.GetClientDetails(configVal);

                        if (createData)
                        {
                            CreateData(matterDetails, clientDetails, configVal);
                        }
                        else
                        {
                            RevertData(matterDetails, clientDetails, configVal);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid Username and Password");
                    }
                }
                else
                {
                    Console.WriteLine("Incorrect command line argument was supplied. Kindly provide correct command line argument.");
                }
                Console.WriteLine("\n\n---Execution completed---");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
            catch (Exception exception)
            {
                Utility.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                Console.WriteLine("Error log will found at {0}", errorFilePath);
                Console.WriteLine("\n\n---Execution completed---");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Example #16
0
 /// <summary>
 /// Main method - Start of the program
 /// </summary>
 /// <param name="args">Command line arguments</param>
 public static void Main(string[] args)
 {
     if (2 == args.Length && !ExcelOperations.IsNullOrEmptyCredential(args[0], args[1]))
     {
         Console.Title = "Update List Permission";
         ErrorMessage.ShowMessage(ConfigurationManager.AppSettings["ExcelMessage"], ErrorMessage.MessageType.Success);
         try
         {
             string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
             string sheetName = ConfigurationManager.AppSettings["SheetName"];
             Collection <Collection <string> > groupSheetValues = ExcelOperations.ReadSheet(filePath, ConfigurationManager.AppSettings["GroupSheetName"]);
             string groupName = Convert.ToString(groupSheetValues[1][0], CultureInfo.InvariantCulture);
             string username  = args[0].Trim();
             string password  = args[1].Trim();
             Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
             if (listval.Count() > 0)
             {
                 // Get Is Deployed on Azure parameter
                 bool isDeployedOnAzure = Convert.ToBoolean(listval["IsDeployedOnAzure"].ToUpperInvariant(), CultureInfo.InvariantCulture);
                 // Get the Client Context
                 using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(listval["CatalogSiteURL"], username, password, isDeployedOnAzure))
                 {
                     try
                     {
                         UpdateListPermissions(groupName, clientContext);
                         ErrorMessage.ShowMessage(ConfigurationManager.AppSettings["ListSuccess"], ErrorMessage.MessageType.Success);
                     }
                     catch (Exception exception)
                     {
                         ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                         ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ListFailure"], errorFilePath), ErrorMessage.MessageType.Error);
                     }
                 }
             }
             else
             {
                 ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: No inputs found");
             }
         }
         catch (Exception exception)
         {
             ErrorLogger.LogErrorToTextFile(errorFilePath, string.Concat(exception.Message, "\n", exception.StackTrace));
         }
     }
     else
     {
         ErrorMessage.ShowMessage(ConfigurationManager.AppSettings["Invalidcredential"], ErrorMessage.MessageType.Error);
     }
 }
Example #17
0
        static void Main(string[] args)
        {
            //List<RootObject> playerList = new List<RootObject>();
            //List<HistorySummary> playerStatList = new List<HistorySummary>();
            List <History> playerStatList = new List <History>();
            List <Element> playerDataList = new List <Element>();
            List <Team>    teamDataList   = new List <Team>();

            GetPlayerStats(playerStatList);
            playerDataList = GetPlayerData();
            teamDataList   = GetTeamData();
            ExcelOperations.PopulateResults(playerDataList, playerStatList, teamDataList);

            Console.WriteLine("Operation Completed");
            Console.ReadKey();
        }
Example #18
0
        private void butKartyTechn_click(object sender, EventArgs e)
        {
            if (DataStorage.currentOrder.orderNo == "")
            {
                MessageBox.Show("Wczytaj lub utwórz zlecenie");
                return;
            }

            bool ledCheck = true;
            var  dtModels = DataStorage.devToolsDb.Where(nc => nc.nc12 == DataStorage.currentOrder.modelId + "00").ToList();

            if (dtModels.Count() == 0)
            {
                MessageBox.Show("Brak danych w DevTools - wpisz ilości LED ręcznie");
                ledCheck = false;
                //........
            }

            Dictionary <string, LedStructForTechnologicSpec> ledForTechCard = DataPreparation.LedForTechCard(ref ledCheck);
            bool nonStandardOrder = false; //false

            if (!ledCheck)
            {
                if (!superuserList.Contains(currentUser))
                {
                    MessageBox.Show("Błąd danych - dioda LED nie neleży do struktury danych." + Environment.NewLine + Environment.NewLine + "Brak uprawnień do stworzenia niestandardowego - tylko Mistrz i Pierwszy Operator");
                    return;
                }

                if (superuserList.Contains(currentUser))
                {
                    MessageBox.Show("Błąd danych - dioda LED nie neleży do struktury danych." + Environment.NewLine + "Należy ręcznie wpisać nazwę, 12NC i ilość diody");
                    nonStandardOrder = true;
                }
            }

            var excPkg = ExcelOperations.GetExcelPackage(DataStorage.currentOrder.modelId);// currentOrder.modelId);

            if (excPkg != null)
            {
                string additionalComment = lProdWerehouseStock.Text != "..." ? $"Wyrób znajduje się na regale: {lProdWerehouseStock.Text}" : "";

                ExcelOperations.FillOutExcelData(DataStorage.currentOrder, ref excPkg, ledForTechCard, nonStandardOrder, additionalComment);
                string tempFile = ExcelOperations.SaveExcelAndReturnPath(excPkg);
                Process.Start(tempFile);
            }
        }
Example #19
0
        public void AddProductsFromExcel(byte[] formData, long storeOrderId)
        {
            try
            {
                ExcelOperations exOp   = new ExcelOperations(_dal);
                string          result = exOp.ReadExceltoDataTable(formData, "OrderProducts", 1);
                if (result.Length == 0)
                {
                    DataTable dt = exOp.ExcelTable;

                    IUniParameter prmStoreOrderId           = _dal.CreateParameter("StoreOrderId", storeOrderId);
                    IEnumerable <StoreOrderDetail> details  = _dal.List <StoreOrderDetail>("WHS_LST_STOREORDERDETAIL_SP", prmStoreOrderId).ToList();
                    IEnumerable <Product>          products = _dal.List <Product>("PRD_LST_PRODUCT_SP").ToList();

                    foreach (DataRow dr in dt.Rows)
                    {
                        var detailRow = details.Where <StoreOrderDetail>(detail => detail.ProductCode == dr[0].ToString()).FirstOrDefault();
                        if (detailRow != null)
                        {
                            var product = products.Where <Product>(row => row.Code == dr[0].ToString()).First();
                            if (detailRow.StoreOrderDetailId > 0)
                            {
                                detailRow.OrderQuantity = (decimal)dr[2] / product.PackageQuantity;
                                _dal.Update <StoreOrderDetail>(detailRow);
                            }
                            else
                            {
                                detailRow.StoreOrder      = storeOrderId;
                                detailRow.Product         = product.ProductId;
                                detailRow.OrderQuantity   = (decimal)dr[2] / product.PackageQuantity;
                                detailRow.ShippedQuantity = (decimal)dr[2] / product.PackageQuantity;
                                detailRow.RevisedQuantity = (decimal)dr[2] / product.PackageQuantity;
                                detailRow.IntakeQuantity  = (decimal)dr[2] / product.PackageQuantity;
                                detailRow.PackageQuantity = product.PackageQuantity;
                                _dal.Create <StoreOrderDetail>(detailRow);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #20
0
            public static void PopulateInCollection(string filename, string sheetName)
            {
                ExcelOperations.ClearData();
                DataTable table = ExcelToDataTable(filename, sheetName);

                for (int row = 1; row <= table.Rows.Count; row++)
                {
                    for (int col = 0; col < table.Columns.Count; col++)
                    {
                        DataCollection dtTable = new DataCollection()
                        {
                            rowNumber = row,
                            colName   = table.Columns[col].ColumnName,
                            colValue  = table.Rows[row - 1][col].ToString()
                        };
                        dataCol.Add(dtTable);
                    }
                }
            }
Example #21
0
 public void ReadingDataFromExcelTestMethod()
 {
     try
     {
         ExcelOperations.PopulateInCollection(
             "C:\\Users\\wchip\\source\\repos\\JPAutomation\\JPAutomation\\AutomationTests\\AutomationTests\\Config\\Messages.xlsx");
         Debug.WriteLine("******************************");
         Debug.WriteLine("First Persons first name is: " + ExcelOperations.ReadData(1, "firstName"));
         Debug.WriteLine("First Persons last name is: " + ExcelOperations.ReadData(1, "lastName"));
         Debug.WriteLine("First Persons email is: " + ExcelOperations.ReadData(1, "email"));
         Debug.WriteLine("First Persons phone is: " + ExcelOperations.ReadData(1, "phone"));
         Debug.WriteLine("First Persons address1 is: " + ExcelOperations.ReadData(1, "address1"));
         Debug.WriteLine("First Persons address2 is: " + ExcelOperations.ReadData(1, "address2"));
         Debug.WriteLine("First Persons state is: " + ExcelOperations.ReadData(1, "state"));
         Debug.WriteLine("First Persons zip code is: " + ExcelOperations.ReadData(1, "zipCode"));
         Debug.WriteLine("First Persons message is: " + ExcelOperations.ReadData(1, "messageBox"));
         Debug.WriteLine("******************************");
         Debug.WriteLine("Second Persons first name is: " + ExcelOperations.ReadData(2, "firstName"));
         Debug.WriteLine("Second Persons last name is: " + ExcelOperations.ReadData(2, "lastName"));
         Debug.WriteLine("Second Persons email is: " + ExcelOperations.ReadData(2, "email"));
         Debug.WriteLine("Second Persons phone is: " + ExcelOperations.ReadData(2, "phone"));
         Debug.WriteLine("Second Persons address1 is: " + ExcelOperations.ReadData(2, "address1"));
         Debug.WriteLine("Second Persons address2 is: " + ExcelOperations.ReadData(2, "address2"));
         Debug.WriteLine("Second Persons state is: " + ExcelOperations.ReadData(2, "state"));
         Debug.WriteLine("Second Persons zip code is: " + ExcelOperations.ReadData(2, "zipCode"));
         Debug.WriteLine("Second Persons message is: " + ExcelOperations.ReadData(2, "messageBox"));
         Debug.WriteLine("******************************");
         Debug.WriteLine("Third Persons first name is: " + ExcelOperations.ReadData(3, "firstName"));
         Debug.WriteLine("Third Persons last name is: " + ExcelOperations.ReadData(3, "lastName"));
         Debug.WriteLine("Third Persons email is: " + ExcelOperations.ReadData(3, "email"));
         Debug.WriteLine("Third Persons phone is: " + ExcelOperations.ReadData(3, "phone"));
         Debug.WriteLine("Third Persons address1 is: " + ExcelOperations.ReadData(3, "address1"));
         Debug.WriteLine("Third Persons address2 is: " + ExcelOperations.ReadData(3, "address2"));
         Debug.WriteLine("Third Persons state is: " + ExcelOperations.ReadData(3, "state"));
         Debug.WriteLine("Third Persons zip code is: " + ExcelOperations.ReadData(3, "zipCode"));
         Debug.WriteLine("Third Persons message is: " + ExcelOperations.ReadData(3, "messageBox"));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
        public void CreateUserAndLoginWithThatUser()
        {
            //Boolean correctPage = false;
            LoginPage    regNow    = new LoginPage(driver);
            HomePageTest hmpg_test = new HomePageTest();

            hmpg_test.CheckNavigationToLoginPage();
            regNow.ClickRegisterNow();
            Assert.AreEqual(driver.SwitchTo().Window(driver.WindowHandles[1]).Url, "https://www.epocrates.com/liteRegistration.do?mode=display&ICID=website"); // url is OK
            UserRegistrationPage ur = new UserRegistrationPage(driver);

            Dictionary <string, string> UserData = ur.GetRegisterUserValuesFromExcel();

            ur.RegisterUserExcel(ur.UserData);
            LandingPage lp = new LandingPage(driver);

            lp.MoveToLoginPage();

            regNow.Login(ExcelOperations.ReadData(1, "Email"), ExcelOperations.ReadData(1, "Password"));
        }
Example #23
0
        /// <summary>
        /// This method is the entry point for the application
        /// </summary>
        /// <param name="args">input from console</param>
        public static void Main(string[] args)
        {
            string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
            string sheetName = ConfigurationManager.AppSettings["configsheetname"];

            if (null != args && 3 <= args.Length)
            {
                string login = args[1], password = args[2];
                if (!ExcelOperations.IsNullOrEmptyCredential(login, password))
                {
                    Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
                    listval.Add("Username", login);
                    listval.Add("Password", password);
                    Collection <Collection <string> > groupSheetValues = ExcelOperations.ReadSheet(filePath, ConfigurationManager.AppSettings["groupsheetname"]);
                    List <DataStorage> groupData = ReadGroupConfig(groupSheetValues, listval);
                    if (args.Length != 0 && !string.IsNullOrWhiteSpace(args[0]))
                    {
                        if (Convert.ToBoolean(args[0], CultureInfo.InvariantCulture))
                        {
                            AddGroups(listval, groupData);
                        }
                        else
                        {
                            DeleteGroups(listval, groupData);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Invalid Credentials.");
                    ErrorLogger.LogErrorToTextFile(errorFilePath, "Exception Details: Invalid Credentials.");
                }
            }
            else
            {
                Console.WriteLine("Insufficient Parameters.");
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Exception Details: Insufficient Parameters.");
            }
        }
Example #24
0
 /// <summary>
 /// Staic main method
 /// </summary>
 /// <param name="args">Command line arguement</param>
 public static void Main(string[] args)
 {
     if (2 == args.Length && !ExcelOperations.IsNullOrEmptyCredential(args[0], args[1]))
     {
         try
         {
             using (ConsoleCopy console_copy = new ConsoleCopy(logfileLocation))
             {
                 string termGroupName            = ConfigurationManager.AppSettings["termGroupName"];
                 string termSetNameClient        = ConfigurationManager.AppSettings["termSetNameClient"];
                 string termSetNamePracticeGroup = ConfigurationManager.AppSettings["termSetNamePracticeGroup"];
                 string practiceGroupFieldName   = ConfigurationManager.AppSettings["practiceGroupFieldName"];
                 string areaOfLawFieldName       = ConfigurationManager.AppSettings["areaOfLawFieldName"];
                 string subareaOfLawColumnName   = ConfigurationManager.AppSettings["subareaOfLawColumnName"];
                 string userName = args[0].Trim();
                 string password = args[1].Trim();
                 List <PracticeGroup> practiceGroups  = new List <PracticeGroup>();
                 List <Client>        clients         = new List <Client>();
                 ClientContext        clientContext   = GetClientContext(userName, password);
                 TaxonomySession      taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                 TermGroup            termGroup       = Utility.LoadTermGroup(clientContext, taxonomySession, termGroupName);
                 clients        = Utility.IntializeClientObject(clientContext, termGroup, termSetNameClient);
                 practiceGroups = Utility.IntializePracticeGroupObject(clientContext, termGroup, termSetNamePracticeGroup);
                 foreach (Client client in clients)
                 {
                     UpdateAllClients(practiceGroupFieldName, areaOfLawFieldName, subareaOfLawColumnName, practiceGroups, client);
                 }
             }
         }
         catch (Exception exception)
         {
             ErrorMessage.ShowMessage(exception.Message, ErrorMessage.MessageType.Error);
         }
     }
     else
     {
         ErrorMessage.ShowMessage("Please enter the username and password", ErrorMessage.MessageType.Error);
     }
 }
Example #25
0
        /// <summary>
        /// This method is the entry point for this application
        /// </summary>
        /// <param name="args">input from console</param>
        private static void Main(string[] args)
        {
            string configSheet = ConfigurationManager.AppSettings["configsheetname"];
            string filePath    = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
            Dictionary <string, string> configVal = ExcelOperations.ReadFromExcel(filePath, configSheet);

            if (2 <= args.Length)
            {
                string login = args[1], password = args[2];
                bool   createSiteCollections = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture);
                configVal.Add("Username", login);
                if (!ExcelOperations.IsNullOrEmptyCredential(login, password))
                {
                    try
                    {
                        Collection <Collection <string> > clientVal = ExcelOperations.ReadSheet(filePath, ConfigurationManager.AppSettings["clientsheetname"]);
                        bool   isDeployedOnAzure = Convert.ToBoolean(configVal["IsDeployedOnAzure"], CultureInfo.InvariantCulture);
                        string targetSite        = configVal["TenantAdminURL"];
                        string tenantSite        = configVal["TenantURL"];

                        using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(targetSite, login, password, isDeployedOnAzure))
                        {
                            using (SecureString securePassword = new SecureString())
                            {
                                foreach (char letter in password)
                                {
                                    securePassword.AppendChar(letter);
                                }
                                SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

                                // Activate feature on tenant site collection
                                ActivateFeature(tenantSite, onlineCredentials);
                                for (int count = 1; count < clientVal.Count; count++)
                                {
                                    string clientName   = clientVal[count][0];
                                    string clientUrl    = clientVal[count][2];
                                    string siteOwners   = clientVal[count][3];
                                    string siteVisitors = clientVal[count][4];
                                    if (createSiteCollections)
                                    {
                                        CreateSiteCollections(clientContext, configVal, clientUrl, clientName);
                                        CreateRestrictedGroup(clientUrl, onlineCredentials);

                                        //// Check if the user list for the group is empty
                                        if (!string.IsNullOrEmpty(siteOwners))
                                        {
                                            AssignPermissions(clientUrl, onlineCredentials, ConfigurationManager.AppSettings["Owners Group"], siteOwners);
                                        }

                                        //// Check if the user list for the group is empty
                                        if (!string.IsNullOrEmpty(siteVisitors))
                                        {
                                            AssignPermissions(clientUrl, onlineCredentials, ConfigurationManager.AppSettings["Visitors Group"], siteVisitors);
                                        }

                                        ActivateFeature(clientUrl, onlineCredentials);
                                    }
                                    else
                                    {
                                        DeleteSiteCollection(clientContext, clientUrl);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorLogger.DisplayErrorMessage(exception.Message);
                    }
                }
            }
            else
            {
                Console.WriteLine("Command-line parameters are missing. Provide {0} Action(true/false) {1} Username and {2} Password");
            }
        }
Example #26
0
        /// <summary>
        /// This method is the entry point for the application
        /// </summary>
        /// <param name="args">input from console</param>
        public static void Main(string[] args)
        {
            if (null != args && 2 <= args.Length)
            {
                string login = args[1].Trim(), password = args[2].Trim();
                bool   createType = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture);
                if (!ExcelOperations.IsNullOrEmptyCredential(login, password))
                {
                    string filePath                     = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
                    string sheetName                    = ConfigurationManager.AppSettings["configsheetname"];
                    string termStoreSheetname           = ConfigurationManager.AppSettings["termstoreSheetname"];
                    Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);

                    // Read from Excel
                    Collection <Collection <string> > termStoreVal = ExcelOperations.ReadSheet(filePath, termStoreSheetname);
                    List <string> contentTypeVal        = new List <string>();
                    List <string> documentTemplateList  = new List <string>();
                    int           contentTypeIndex      = termStoreVal[0].IndexOf(ConfigurationManager.AppSettings["contentTypeColumnName"]);
                    int           documentTemplateIndex = termStoreVal[0].IndexOf(ConfigurationManager.AppSettings["documentTemplateColumnName"]);

                    for (int count = 1; count < termStoreVal.Count; count++)
                    {
                        if (!contentTypeVal.Contains(termStoreVal[count][contentTypeIndex]))
                        {
                            contentTypeVal.Add(termStoreVal[count][contentTypeIndex]);
                        }
                        documentTemplateList = documentTemplateList.Union(termStoreVal[count][documentTemplateIndex].Split(';')).ToList();
                    }
                    contentTypeVal = contentTypeVal.Union(documentTemplateList).ToList();

                    try
                    {
                        if (0 != listval.Count)
                        {
                            string        targetSite    = listval["ContentTypeHubURL"]; // Get the URL of site collection
                            ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(targetSite, login, password);

                            for (int count = 0; count < contentTypeVal.Count; count++)
                            {
                                string parentContentType = ConfigurationManager.AppSettings["ContentTypeValue"];
                                string contentType       = contentTypeVal[count];                                     // Get Content Type DMS from Excel
                                string contentTypeGroup  = ConfigurationManager.AppSettings["ContentTypeGroupValue"]; // Get Group of Content Type
                                if (createType)
                                {
                                    CreateContentType(clientContext, contentType, parentContentType, contentTypeGroup);
                                }
                                else
                                {
                                    DeleteContentType(clientContext, contentType);
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                    }
                }
                else
                {
                    ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Invalid Credentials");
                }
            }
            else
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: Insufficient Parameters");
            }
        }
Example #27
0
        /*Section="CustomCodeRegion"*/
        #region Customized
        public void LoadLoomisFile(byte[] formData)
        {
            using (IDAL dal = this.DAL)
            {
                dal.BeginTransaction();
                try
                {
                    _logger.Debug($"Loomis Transfer file read started : {DateTime.Now.ToLongTimeString()}");
                    ExcelOperations exOp           = new ExcelOperations(dal);
                    long            eventId        = _parameterReader.ReadEventId("System");
                    long            organizationId = OTApplication.Context.Organization.Id;
                    string          result         = exOp.ReadExceltoDataTable(formData, "Loomis", 1);
                    DataTable       dt             = exOp.ExcelTable;
                    if (result.Length == 0 && dt.Rows.Count > 0) // if no error and there are records in excel
                    {
                        // find min max dates from excel datatable
                        DateTime minDate, maxDate;
                        minDate = (DateTime)dt.Rows[0]["SAYIMTARIHI"];
                        maxDate = (DateTime)dt.Rows[0]["SAYIMTARIHI"];
                        foreach (DataRow dr in dt.Rows)
                        {
                            DateTime saleDate = (DateTime)dr["SAYIMTARIHI"];
                            if (saleDate < minDate)
                            {
                                minDate = saleDate;
                            }
                            if (saleDate > maxDate)
                            {
                                maxDate = saleDate;
                            }
                        }
                        _logger.Debug($"Min and Max Dates found in excel file minDate = {minDate.ToString("dd.MM.yyyy")} maxDate = {maxDate.ToString("dd.MM.yyyy")}: {DateTime.Now.ToLongTimeString()}");

                        // read current records in Maktech DB
                        IUniParameter  prmStartDate   = dal.CreateParameter("StartDate", minDate);
                        IUniParameter  prmEndDate     = dal.CreateParameter("EndDate", maxDate);
                        IList <Loomis> maktechRecords = dal.List <Loomis>("ACC_LST_LOOMISALL_SP", prmStartDate, prmEndDate).ToList();
                        _logger.Debug($"Maktech records was read: {DateTime.Now.ToLongTimeString()}");


                        // process all rows to Maktech DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            DateTime saleDate     = (DateTime)dr["SAYIMTARIHI"];
                            int      store        = int.Parse(dr["HNKODU"].ToString());
                            decimal  actualAmount = (decimal)dr["SAYILAN"];
                            string   sealNo       = dr["MUHURNO"].ToString().Trim();

                            if (sealNo == "0" || sealNo.Length == 0)
                            {
                                continue;
                            }

                            var storedayrec = maktechRecords.Where(o => (o.Store == store && o.LoomisDate == saleDate));

                            /* update aynı tarih ve mağazalı 2 kayıtın toplamını değil, sonuncusunu aldığından problem oluyor, kapatıyorum. Taylan - 2020-01-20
                             * // Taylan - 2020-01-17 : Bu kısım kapalıydı, niye kapattığımı hatırlamıyorum ama güncellenmesi gerektiğinden tekrar açıyorum.
                             * if (storedayrec.Count() > 0)
                             * {
                             *  Loomis updateRec = storedayrec.First();
                             *  if (updateRec.ActualAmount != actualAmount)
                             *  {
                             *      updateRec.ActualAmount = actualAmount;
                             *      dal.Update(updateRec);
                             *  }
                             * }
                             */

                            if (storedayrec.Count() == 0)
                            {
                                Loomis createRec = new Loomis();
                                createRec.SaleDate     = saleDate.AddDays(-1);
                                createRec.LoomisDate   = saleDate;
                                createRec.Store        = store;
                                createRec.ActualAmount = actualAmount;
                                if (dr["BEYANEDILEN"] != DBNull.Value)
                                {
                                    createRec.DeclaredAmount = (decimal)dr["BEYANEDILEN"];
                                }
                                else
                                {
                                    createRec.DeclaredAmount = null;
                                }
                                createRec.FakeAmount      = (decimal)dr["GECERSIZ"];
                                createRec.SealNo          = sealNo;
                                createRec.Explanation     = dr["ACIKLAMA"].ToString();
                                createRec.MikroStatusCode = 0;
                                createRec.Organization    = organizationId;
                                createRec.Event           = eventId;
                                dal.Create(createRec);
                            }
                        }
                        _logger.Debug($"All rows processed : {DateTime.Now.ToLongTimeString()}");

                        dal.CommitTransaction();
                    }
                    else if (result.Length > 0)
                    {
                        throw new Exception(result);
                    }
                }
                catch (Exception ex)
                {
                    dal.RollbackTransaction();
                    _logger.Error($" ServiceName : LoomisService, MethodName : LoadLoomisFile, Exception : {ex.Message}");
                    throw ex;
                }
            }
        }
Example #28
0
        /// <summary>
        /// Main method - Start of the program
        /// </summary>
        /// <param name="args"> argument as parameter </param>
        public static void Main(string[] args)
        {
            if (2 <= args.Length && !ExcelOperations.IsNullOrEmptyCredential(args[0], args[1]))
            {
                try
                {
                    // Read login credentials from excel
                    string filePath  = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\" + ConfigurationManager.AppSettings["filename"];
                    string sheetName = ConfigurationManager.AppSettings["SheetName"];
                    Dictionary <string, string> listval = ExcelOperations.ReadFromExcel(filePath, sheetName);
                    bool   isDeployedOnAzure            = Convert.ToBoolean(listval["IsDeployedOnAzure"], CultureInfo.InvariantCulture);
                    string username = args[0].Trim();
                    string password = args[1].Trim();

                    // Read client context for Tenant URL
                    using (ClientContext userClientContext = ConfigureSharePointContext.ConfigureClientContext(listval["CatalogSiteURL"], username, password, isDeployedOnAzure))
                    {
                        // Reading SharePoint properties
                        string groupName         = ConfigurationManager.AppSettings["PracticeGroupName"]; // Get Practice Group Name
                        string termSetName       = ConfigurationManager.AppSettings["TermSetName"];       // Get Term Set Name
                        string clientIdProperty  = ConfigurationManager.AppSettings["ClientIDProperty"];  // Get Client ID
                        string clientUrlProperty = ConfigurationManager.AppSettings["ClientUrlProperty"]; // Get Client Url
                        string clientUrl         = null;                                                  // Store Client URL
                        string selectedField     = null;

                        // Reading client term sets
                        ClientTermSets clientTermSets = TermStoreOperations.GetClientDetails(userClientContext, groupName, termSetName, clientIdProperty, clientUrlProperty);

                        // Iterating over clients in term store to get client URL and update lists
                        foreach (Client client in clientTermSets.ClientTerms)
                        {
                            try
                            {
                                clientUrl = client.ClientUrl;
                                if (!string.IsNullOrEmpty(clientUrl))
                                {
                                    ClientContext  clientContext = ConfigureSharePointContext.ConfigureClientContext(clientUrl, username, password, isDeployedOnAzure);
                                    List           list          = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["ListName"]);
                                    ViewCollection viewFields    = list.Views;
                                    View           targetView    = viewFields.GetByTitle(ConfigurationManager.AppSettings["ViewName"]);
                                    clientContext.Load(targetView.ViewFields);
                                    clientContext.ExecuteQuery();

                                    // Update fields to list only if title field is not present already
                                    selectedField = UpdateFields(selectedField, client, clientContext, list, targetView);
                                }

                                ErrorMessage.ShowMessage(client.ClientName + " site collection view updated with field", ErrorMessage.MessageType.Success);
                            }
                            catch (Exception exception)
                            {
                                ErrorMessage.ShowMessage(exception.Message + client.ClientName, ErrorMessage.MessageType.Error);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    ErrorMessage.ShowMessage(exception.Message, ErrorMessage.MessageType.Error);
                }
            }
            else
            {
                ErrorMessage.ShowMessage("Please enter the Username and Password", ErrorMessage.MessageType.Error);
            }
        }
        /*Section="CustomCodeRegion"*/
        #region Customized

        public string LoadBankStatementFile(byte[] formData, string bankName)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("tr-TR");

            using (IDAL dal = this.DAL)
            {
                dal.BeginTransaction();
                try
                {
                    //_logger.Debug($"Bank Statement file read started : {DateTime.Now.ToLongTimeString()}");
                    ExcelOperations exOp           = new ExcelOperations(dal);
                    long            eventId        = _parameterReader.ReadEventId("System");
                    long            organizationId = OTApplication.Context.Organization.Id;
                    string          result         = "";
                    int             bankId         = -1;

                    switch (bankName)
                    {
                    case "TEB": bankId = 1; exOp.ReadExceltoDataTable(formData, "TEB Bank Statement", 1); break;

                    case "Vakıfbank": bankId = 2; result = exOp.ReadExceltoDataTable(formData, "Vakıf Bank Statement", 1); break;

                    case "ING Bank": bankId = 3; result = exOp.ReadExceltoDataTable(formData, "ING Bank Statement", 1); break;
                    }


                    //if (result.Length == 0)
                    //{
                    DataTable             dt = exOp.ExcelTable;
                    IList <BankStatement> t  = new List <BankStatement>();

                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["Tarih"].GetType().Equals(System.Type.GetType("System.DateTime")))
                        {
                            BankStatement pt = new BankStatement();

                            pt.Bank              = bankId; //Vakifbank ID
                            pt.Date              = (DateTime)dr["Tarih"];
                            pt.Description       = dr["Açıklama"].ToString();
                            pt.TransactionAmount = (decimal)dr["Tutar"];
                            pt.Balance           = (decimal)dr["Bakiye"];
                            pt.Channel           = dr["Kanal"].ToString();
                            pt.Event             = eventId;
                            pt.Organization      = organizationId;

                            t.Add(pt);
                        }

                        //_logger.Debug($"File read to dataobject array : {DateTime.Now.ToLongTimeString()}");
                    }

                    foreach (BankStatement rec in t)
                    {
                        dal.Create <BankStatement>(rec);
                    }


                    if (result.Length == 0)
                    {
                        dal.CommitTransaction();
                    }
                    else
                    {
                        dal.RollbackTransaction();
                        throw new Exception(result);
                    }
                    //}
                    return("");
                }
                catch (Exception ex)
                {
                    dal.RollbackTransaction();
                    _logger.Error($"servicename : BankStatementService method : LoadINGBankStatementFile exception : {ex.ToString()}");
                    throw ex;
                    // return "Dosyayı kontrol ediniz";
                }
            }
        }
Example #30
0
        /*Section="CustomCodeRegion"*/
        #region Customized
        // Keep your custom code in this region.
        public string LoadWorkingHoursFile(byte[] formData)
        {
            using (IDAL dal = this.DAL)
            {
                dal.BeginTransaction();
                try
                {
                    _logger.Debug($"WorkingHour file read started : {DateTime.Now.ToLongTimeString()}");
                    ExcelOperations exOp = new ExcelOperations(dal);

                    DateTime reportDate;

                    // get report date
                    try
                    {
                        reportDate = DateTime.ParseExact(
                            exOp.GetSpesificCellContent(formData, "WorkingHours", 18, 8).Substring(0, 10),
                            "dd.MM.yyyy",
                            System.Globalization.CultureInfo.GetCultureInfo("en-US")
                            );
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"serviceName : WorkingHoursService, methodName : LoadWorkingHoursFile, Datetime parsing failed, Exception : {ex.Message}");
                        throw new Exception($"Datetime parsing failed, Exception : {ex.Message}");
                    }

                    string result = exOp.ReadExceltoDataTable(formData, "WorkingHours", 1); // filetype 1: xlsx
                    if (result.Length == 0)
                    {
                        DataTable            dt         = exOp.ExcelTable;
                        IList <WorkingHours> whFailList = new List <WorkingHours>();

                        WorkingHours wh = new WorkingHours();
                        wh.Organization = OTApplication.Context.Organization.Id;
                        wh.Event        = _parameterReader.ReadEventId("Import Workinghours");

                        foreach (DataRow dr in dt.Rows)
                        {
                            // InnerRows
                            IList <string> openUserList    = dr["ACAN"].ToString().Trim().Split('\n').ToList();
                            IList <string> closeUserList   = dr["KAPATAN"].ToString().Trim().Split('\n').ToList();
                            IList <string> openingTimeList = dr["ACILISZAMANI"].ToString().Trim().Split('\n').ToList();
                            IList <string> closingTimeList = dr["KAPANISZAMANI"].ToString().Trim().Split('\n').ToList();

                            wh.StoreCode = dr["ABONENO"].ToString();
                            wh.StoreName = dr["ABONEADI"].ToString();
                            wh.Note      = dr["NOTLAR"].ToString();

                            var processWorkingHoursResultTuple = processWorkingHours(dr, reportDate, whFailList, wh, openUserList, closeUserList, openingTimeList, closingTimeList);
                            if (processWorkingHoursResultTuple.Item1)
                            {
                                updateYesterdayRecord(dal, reportDate, wh, openUserList, closeUserList, openingTimeList, closingTimeList);
                            }
                            if (processWorkingHoursResultTuple.Item2)
                            {
                                insertWorkingHours(dal, reportDate, wh, openUserList, closeUserList, openingTimeList, closingTimeList);
                            }
                        }
                        if (whFailList.Count > 0)
                        {
                            result = $"{dt.Rows.Count } kaydın {whFailList.Count} adedi aktarılamadı. Lütfen kayıtları kontrol ediniz.";
                        }
                        if (String.IsNullOrEmpty(result))
                        {
                            _logger.Debug($"WorkingHour file read finished : {DateTime.Now.ToLongTimeString()}");
                        }
                    }
                    dal.CommitTransaction();
                    return(result);
                }
                catch (Exception ex)
                {
                    dal.RollbackTransaction();
                    throw ex;
                }
            }
        }