public ActionResult Index(string searchTerm, int page = 1)
        {
            searchTerm = StringManipulation.CapitalizeName(searchTerm);
            string result;

            if (string.IsNullOrEmpty(searchTerm))
            {
                result = _foodAppService.GetAllPaginated(page, 20);
            }
            else
            {
                ICollection <QueryFilter> filters = new List <QueryFilter>();
                QueryFilter filter = new QueryFilter("Name", searchTerm, Operator.StartsWith);
                filters.Add(filter);

                result = _foodAppService.FindPaginated(filters, page, 20);
            }

            PaginationEntity <FoodVm> foodsPaginated = string.IsNullOrEmpty(result)
                ? new PaginationEntity <FoodVm>()
                : JsonConvert.DeserializeObject <PaginationEntity <FoodVm> >(result);

            SerializablePagedList <FoodVm> list    = new SerializablePagedList <FoodVm>(foodsPaginated.Items, page, 20, foodsPaginated.MetaData.TotalItemCount);
            IPagedList <FoodVm>            foodVms = list;

            if (Request.IsAjaxRequest())
            {
                return(PartialView("_foodTable", foodVms));
            }
            return(View(foodVms));
        }
Ejemplo n.º 2
0
        private void CountWords()
        {
            int ctrIndex    = 65; // starting numeric index of a alphabet, 65=a, 66=b etc
            int ctrIndexMax = 90; // last numeric index of a alphabet, 90=z
            int multiplier  = 1;

            foreach (var word in WordList)
            {
                var wc = new WordCounter();
                wc.FindWordInList(word, ParagraphList);

                string joined = StringManipulation.Join(",", wc.wordInParagraph);

                string alphabet = StringManipulation.IntToAlphabet(ctrIndex);

                string strIndex = new StringBuilder().Insert(0, alphabet, multiplier).ToString();

                Console.WriteLine($"{strIndex}. {word} {{{wc.frequency.ToString()}:{joined}}})");

                if (ctrIndex == ctrIndexMax)
                {
                    ctrIndex = 65;
                    multiplier++;
                }
                else
                {
                    ctrIndex++;
                }
            }
            Console.ReadLine();
        }
Ejemplo n.º 3
0
        public void ShouldOrderFlatternThings()
        {
            var thingList = new List <Thing> {
                new Thing("beans", 4)
                {
                    ChildThings = new List <Thing> {
                        new Thing("eggs", 1)
                        {
                            ChildThings = new List <Thing> {
                                new Thing("Crap", 999999)
                            }
                        }
                    }
                }
            };


            var flat   = StringManipulation.Flattern(thingList);
            var result = flat.OrderByValueAsc();

            result[0].Name.Should().Be("eggs");
            result[0].Value.Should().Be(1);
            result[1].Name.Should().Be("beans");
            result[1].Value.Should().Be(4);
            result[2].Name.Should().Be("Crap");
            result[2].Value.Should().Be(999999);
        }
Ejemplo n.º 4
0
        public T FindbyName(string name)
        {
            Customer customer = null;

            using (DBClass = new MSSQLDatabase())
            {
                var cmd = DBClass.GetStoredProcedureCommand("APP_GET_CUSTOMER_BY_NAME") as SqlCommand;
                DBClass.AddSimpleParameter(cmd, "@Name", name);
                var reader = DBClass.ExecuteReader(cmd);
                while (reader.Read())
                {
                    customer               = new Customer();
                    customer.CustomerID    = int.Parse(reader[0].ToString());
                    customer.FirstName     = StringManipulation.UppercaseFirst(reader[1].ToString());
                    customer.LastName      = StringManipulation.UppercaseFirst(reader[2].ToString());
                    customer.Address       = reader[3].ToString();
                    customer.Phone         = reader[4].ToString();
                    customer.MobilePhone   = reader[5].ToString();
                    customer.Email         = reader[6].ToString();
                    customer.DepartementID = int.Parse(reader[7].ToString());
                    customer.StatusId      = int.Parse(reader[8].ToString());
                    customer.Active        = bool.Parse(reader[9].ToString());
                    customer.CreditLimit   = decimal.Parse(reader[10].ToString());
                }
            }
            return(customer as T);
        }
Ejemplo n.º 5
0
        public static void Main(string[] args)
        {
            initialization();

            if (Convert.ToDateTime(DateTime.Now.ToShortDateString()) < Convert.ToDateTime("2018/8/31"))
            {
                Console.WriteLine("还没有到查看的时间哦\n");
            }
            else
            {
                Thread.Sleep(9000);
                for (int i = 1; i <= StringManipulation.Len(test); i++)
                {
                    WriteLetter(StringManipulation.Mid(test, i, 1));
                }

                WriteLetter(" ");

                Console.WriteLine("生日快乐哦\n");
            }

            for (int i = 0; i < 3; i++)
            {
                Console.Write(".");

                Thread.Sleep(5000);
            }

            Console.WriteLine("\n");

            Console.WriteLine("按Enter键退出");

            Console.ReadKey();
        }
Ejemplo n.º 6
0
        public override void Emit(SsisEmitterContext context)
        {
            context.Package.DtsPackage.EnableConfigurations = true;

            string packageRoot =
                String.IsNullOrEmpty(PackageConfigurationPath)
                ? Settings.Default.DetegoPackageConfigurationRoot
                : PackageConfigurationPath;

            string configFilePath = StringManipulation.CleanPath(packageRoot
                                                                 + Path.DirectorySeparatorChar
                                                                 + Name
                                                                 + "."
                                                                 + Resources.ExtensionDtsConfigurationFile);

            MessageEngine.Trace(Severity.Debug, "Adding Configuration File {0}", configFilePath);
            if (!context.Package.DtsPackage.Configurations.Contains(Name))
            {
                DTS.Configuration config = context.Package.DtsPackage.Configurations.Add();
                config.ConfigurationType = DTS.DTSConfigurationType.ConfigFile;
                config.Name                = Name;
                config.Description         = Name;
                config.ConfigurationString = configFilePath;
                context.Package.DtsPackage.ImportConfigurationFile(configFilePath);
            }
        }
        public static string ToShaString(this String s)
        {
            var data = SHA1.EncryptBase64(s);
            var str  = StringManipulation.UrlEncode(Encoding.GetEncoding("iso-8859-1").GetString(data, 0, data.Length));

            return(str);
        }
Ejemplo n.º 8
0
        public Package(AST.Task.AstPackageNode astNode)
            : base(astNode)
        {
            _DTSApplication        = new DTS.Application();
            DtsPackage             = new DTS.Package();
            DtsPackage.Name        = StringManipulation.NameCleaner(Name);
            PackageType            = String.IsNullOrEmpty(astNode.PackageType) ? "ETL" : astNode.PackageType;
            PackageFolder          = astNode.PackageFolder;
            PackagePath            = astNode.PackagePath;
            PackageProtectionLevel = astNode.ProtectionLevel;
            PackagePassword        = astNode.PackagePassword;

            // vsabella: We thought about adding this in the Lowering phase.
            // The reason this was not placed in Lowering is that this variable must be available
            // before any other lowering can take place.  Additionally i needed a single place where the
            // variable name could remain constant and other lowering phase engines could refer to it.
            // PreEmit
            PackageRootVariable =
                new Variable(PackagePathRootVariableName)
            {
                InheritFromPackageParentConfigurationString = "User::" + PackagePathRootVariableName,
                ValueString = PathManager.TargetPath,
                TypeCode    = TypeCode.String
            };

            Children.Add(PackageRootVariable);
        }
Ejemplo n.º 9
0
        public void Test_ReadAndWriteToBinaryFile()
        {
            SHA256                   shaM        = new SHA256Managed();
            StringManipulation       stringManip = new StringManipulation();
            List <SerializedProcess> processes   = new List <SerializedProcess>();
            SerializedProcess        sprocess    = new SerializedProcess();

            byte[] result;
            result = shaM.ComputeHash(stringManip.ToByteArray("Test 3"));
            Debug.WriteLine(result);
            Debug.WriteLine(stringManip.ByteArrayToString(result));
            sprocess.Name = stringManip.ByteArrayToString(result);
            processes.Add(sprocess);
            sprocess      = new SerializedProcess();
            result        = shaM.ComputeHash(stringManip.ToByteArray("Test 4"));
            sprocess.Name = stringManip.ByteArrayToString(result);
            processes.Add(sprocess);
            String binaryPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ProcessesBinary.bin";

            writeFile.WriteToBinaryFile <List <SerializedProcess> >(binaryPath, processes, false);
            List <SerializedProcess> readProcesses = new List <SerializedProcess>();

            readProcesses = writeFile.ReadFromBinaryFile <List <SerializedProcess> >(binaryPath);
            CollectionAssert.AreEqual(processes, readProcesses, new SerializedProcess_Comparer());
        }
Ejemplo n.º 10
0
 protected override void CheckResponseForErrors(Dictionary <string, dynamic> responseContent)
 {
     if (responseContent.ContainsKey("error"))
     {
         throw new WebException(StringManipulation.AppendPeriodIfNecessary("There was a problem connecting to the " + Name + " api: " + (string)responseContent["error"]));
     }
 }
Ejemplo n.º 11
0
        public override void DeleteOrder(string orderId)
        {
            BitstampRequest deleteOrderRequest = new BitstampRequest(DeleteOrderPath, _apiInfo);

            deleteOrderRequest.AddParameter("id", orderId);

            //Can't call ApiPost, because this request does not return a dictionary unless there is an error.
            RestClient client = new RestClient {
                BaseUrl = new Uri(BaseUrl)
            };
            IRestResponse response = client.Execute(deleteOrderRequest);

            //Don't think this can happen, but just in case
            if (response == null)
            {
                throw new Exception("Could not delete order " + orderId + " for " + Name + "; did not get a response back from the api.");
            }

            //If the response is anything other than 'true,' something went wrong. Extract the error message and throw an exception.
            if (!response.Content.Equals("true", StringComparison.InvariantCultureIgnoreCase))
            {
                //Extract the error message
                Dictionary <string, dynamic> returnedContent = new JavaScriptSerializer().Deserialize <Dictionary <string, dynamic> >(response.Content);
                string errorMessage = StringManipulation.AppendPeriodIfNecessary((string)returnedContent["error"]);

                throw new Exception("Problem deleting order " + orderId + " for " + Name + ": " + errorMessage);
            }

            //If the response just contains the word 'true', then the delete was successful.
        }
Ejemplo n.º 12
0
        protected override void CheckResponseForErrors(Dictionary <string, dynamic> responseContent)
        {
            if ((string)GetValueFromResponseResult(responseContent, "result") == "error")
            {
                string message = "There was a problem connecting to the " + Name + " api: ";

                //Get the error message from the response and throw an error. It may either be in 'error', or 'data.'
                if (responseContent.ContainsKey("error"))
                {
                    message += responseContent["error"];
                }
                else if (responseContent.ContainsKey("data"))
                {
                    responseContent = responseContent["data"];
                    message        += (string)GetValueFromResponseResult(responseContent, "message");
                }
                else
                {
                    message += "unknown error.";
                }

                message = StringManipulation.AppendPeriodIfNecessary(message);
                throw new Exception(message);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Adds Two Numbers.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        public Sum(string a, string b)
        {
            int number1, number2;

            number1 = a[0];
            number2 = b[0];
            StringManipulation manipulationObj = new StringManipulation();

            a = manipulationObj.ReverseString(a);
            b = manipulationObj.ReverseString(b);

            a = a.TrimEnd('-');
            b = b.TrimEnd('-');

            Addition addObj = new Addition();

            if (number1 == 45 && number2 == 45)
            {
                addObj.AddNegativeNumbers(a, b);
            }
            else if (number1 == 45 && number2 != 45)
            {
                addObj.AddOneNegativeNumber(a, b);
            }
            else if (number1 != 45 && number2 == 45)
            {
                addObj.AddOneNegativeNumber(a, b);
            }
            else if (number1 != 45 && number2 != 45)
            {
                addObj.AddPositiveNumbers(a, b);
            }
        }
Ejemplo n.º 14
0
        public void NotEqualsOperator(string inputA, string inputB, bool expectedResult)
        {
            var smA = new StringManipulation(inputA);
            var smB = new StringManipulation(inputB);

            Assert.Equal(expectedResult, smA != smB);
        }
Ejemplo n.º 15
0
        public IEnumerable <T> FindAll(List <Dictionary <string, object> > keyValueParam)
        {
            var result = new List <Customer>();

            using (DBClass = new MSSQLDatabase())
            {
                var cmd = DBClass.GetStoredProcedureCommand("APP_GET_ALL_CUSTOMER") as SqlCommand;
                RoutinesParameterSetter.Set(ref cmd, keyValueParam);
                var reader = DBClass.ExecuteReader(cmd);
                while (reader.Read())
                {
                    var customer = new Customer();
                    customer.CustomerID      = int.Parse(reader[0].ToString());
                    customer.FirstName       = StringManipulation.UppercaseFirst(reader[1].ToString());
                    customer.LastName        = StringManipulation.UppercaseFirst(reader[2].ToString());
                    customer.Address         = reader[3].ToString();
                    customer.Phone           = reader[4].ToString();
                    customer.MobilePhone     = reader[5].ToString();
                    customer.Email           = reader[6].ToString();
                    customer.DepartementName = reader[7].ToString();
                    customer.StatusName      = reader[8].ToString();
                    customer.Active          = bool.Parse(reader[9].ToString());
                    result.Add(customer);
                }
            }
            return(result as List <T>);
        }
Ejemplo n.º 16
0
        public void ShiftLeftAndRight(string input, int leftShift, int rightShift, string expectedOutput)
        {
            var sm   = new StringManipulation(input);
            var temp = sm >> leftShift;

            Assert.Equal(new StringManipulation(expectedOutput), sm << rightShift);
        }
 private string ValidateNode(HtmlDocument doc, string queryNode, bool shouldGetAttribute = false, string attribute = "")
 {
     try
     {
         var node = doc.DocumentNode.SelectNodes(queryNode).FirstOrDefault();
         if (node != null)
         {
             if (shouldGetAttribute)
             {
                 return(StringManipulation.ReplaceEncodingString(node.GetAttributeValue(attribute, "")));
             }
             else
             {
                 return(StringManipulation.ReplaceEncodingString(node.InnerHtml));
             }
         }
         else
         {
             return(null);
         }
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 18
0
        public void Start(Writefile writeFile, string binaryPath)
        {
            List <SerializedProcess> readProcesses = new List <SerializedProcess>();

            readProcesses = writeFile.ReadFromBinaryFile <List <SerializedProcess> >(binaryPath);
            Process[]          processlist = Process.GetProcesses();
            byte[]             result;
            Encryption         encryptionManager = new Encryption();
            StringManipulation stringManipulator = new StringManipulation();

            foreach (Process process in processlist)
            {
                Boolean found = false;
                result = encryptionManager.generateHash(process.ProcessName);
                string            processName       = stringManipulator.ByteArrayToString(result);
                SerializedProcess serializedProcess = new SerializedProcess();
                serializedProcess.Name = processName;
                int index = readProcesses.FindIndex(processList => processList.Name == serializedProcess.Name);
                if (index > -1)
                {
                    found = true;
                }
                if (!found)
                {
                    process.Kill();
                }
            }
        }
Ejemplo n.º 19
0
        } /*End of checkIfFileExists method*/

        /*Downloads a file from an SFTP server and writes it to another network location*/
        public IProcessResult <T> DownloadFile <T>(string remoteFilePath, string remoteFileNameParam,
                                                   string localFilePathParam, string localFileNameParam,
                                                   Func <bool, T> statusCheck, bool overrideFile = false,
                                                   Func <string, string> customFileName          = null,
                                                   bool closeConnection = false)
        {
            try
            {
                /*Test the connection to the SFTP site if one does not exist then attempt to establish a new connection*/
                var connectionResult = Connect(statusCheck);
                if (connectionResult.ProcessResultValue.Equals(statusCheck.Invoke(true)) == false)
                {
                    return(ProcessResultWithState(false, statusCheck.Invoke(false)
                                                  , connectionResult.ProcessResultMessage, connectionResult.ProcessResultException));
                }

                //var fullFilePath = Path.Combine(localFilePathParam, localFileNameParam);
                var fullFilePath = Path.Combine(localFilePathParam
                                                , customFileName == null
                                            ? localFileNameParam
                                            : customFileName.Invoke(localFileNameParam));

                /*Create the directory to store the file*/
                Directory.CreateDirectory(localFilePathParam);

                var destinationFilePath = StringManipulation.PathCombine(
                    remoteFilePath, paths: new[] { remoteFileNameParam });

                var fileExists = SftpConnection.Exists(destinationFilePath);

                if (fileExists)
                {
                    using (var file = File.Open(fullFilePath, overrideFile ? FileMode.Create : FileMode.CreateNew))
                    {
                        SftpConnection.DownloadFile(destinationFilePath, file);
                    }
                }

                /*Check to see if the file was successfully created*/
                var downloadResult = File.Exists(fullFilePath);

                /*close connection if requested*/
                if (closeConnection)
                {
                    CloseConnection();
                }

                return(ProcessResultWithState(downloadResult
                                              , statusCheck.Invoke(downloadResult)
                                              , downloadResult
                        ? $"The file: {remoteFileNameParam} was downloaded successfully"
                        : $"The file: {remoteFileNameParam} was NOT downloaded successfully"));
            }
            catch (Exception ex)
            {
                return(ProcessResultWithState(false, statusCheck.Invoke(false)
                                              , $"The file: {remoteFileNameParam} was not downloaded because and exception occurred.", ex));
            }
        } /*End of downloadFile method*/
Ejemplo n.º 20
0
        public void GivenWhiteSpace_ShouldReturnNull(string str1, string str2)
        {
            // Act
            var areAnagrams = StringManipulation.AreAnagrams(str1, str2);

            // Assert
            areAnagrams.Should().BeFalse();
        }
Ejemplo n.º 21
0
        public void GivenAWhiteSpace_ShouldReturnFalse()
        {
            // Act
            var isPalindrome = StringManipulation.IsPalindrome("");

            // Assert
            isPalindrome.Should().BeFalse();
        }
Ejemplo n.º 22
0
        public void GivenNull_ShouldReturnFalse()
        {
            // Act
            var isPalindrome = StringManipulation.IsPalindrome(null);

            // Assert
            isPalindrome.Should().BeFalse();
        }
Ejemplo n.º 23
0
        public void GivenAWord_WhenIsNotPalindrome_ShouldReturnFalse(string str)
        {
            // Act
            var isPalindrome = StringManipulation.IsPalindrome(str);

            // Assert
            isPalindrome.Should().BeFalse();
        }
Ejemplo n.º 24
0
        public void MultiSpaceCheck()
        {
            StringManipulation str = new StringManipulation();

            str.MainString = "    Just     one     space     more     ";

            Assert.AreEqual("space", str.FindWord(3));
        }
Ejemplo n.º 25
0
 public void StringManipulation_NoSpace_BasicTests()
 {
     Assert.AreEqual("8j8mBliB8gimjB8B8jlB", StringManipulation.NoSpace("8 j 8   mBliB8g  imjB8B8  jl  B"));
     Assert.AreEqual("88Bifk8hB8BB8BBBB888chl8BhBfd", StringManipulation.NoSpace("8 8 Bi fk8h B 8 BB8B B B  B888 c hl8 BhB fd"));
     Assert.AreEqual("8aaaaaddddr", StringManipulation.NoSpace("8aaaaa dddd r     "));
     Assert.AreEqual("jfBmgklf8hg88lbe8", StringManipulation.NoSpace("jfBm  gk lf8hg  88lbe8 "));
     Assert.AreEqual("8jaam", StringManipulation.NoSpace("8j aam"));
 }
Ejemplo n.º 26
0
        public void GivenTwoWords_WhenOneIsRotationOfOther_ShouldReturnTrue(string wordA, string wordB)
        {
            // Act
            var isRotation = StringManipulation.IsRotation(wordA, wordB);

            // Assert
            isRotation.Should().BeTrue();
        }
Ejemplo n.º 27
0
        public void GivenTwoStrings_WhenTheyAreAnagram_ShouldReturnTrue(string str1, string str2)
        {
            // Act
            var isAnagram = StringManipulation.AreAnagrams(str1, str2);

            // Assert
            isAnagram.Should().BeTrue();
        }
Ejemplo n.º 28
0
        public void ShouldReverseString()
        {
            var sut = new StringManipulation();

            var reversedString = sut.ReverseString("iman");

            Assert.Equal("nami", reversedString);
        }
Ejemplo n.º 29
0
        public void ReverseWithDashCorrectResultSingleWord()
        {
            var input = "hello";

            var result = StringManipulation.ReverseWithDash(input);

            Assert.IsTrue(String.Equals(result, "o-l-l-e-h"));
        }
Ejemplo n.º 30
0
        public void GivenTwoWords_WhenTheyAreNotAnagrams_ShouldReturnFalse(string a, string b)
        {
            // Act
            var areAnagrams = StringManipulation.AreAnagrams(a, b);

            // Assert
            areAnagrams.Should().BeFalse();
        }