Ejemplo n.º 1
0
        public static IPFrame ToIPFrame(UdpFrame frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }
            if (frame.AddressFamily != AddressFamily.InterNetwork)
            {
                throw new ArgumentNullException("UDP frames of this address family type are not supported.");
            }
            if (frame.Payload.Length <= 0)
            {
                return(null);
            }
            int offset      = sizeof(udp_hdr);
            int payload_len = frame.Payload.Length;

            byte[] message = new byte[offset + payload_len];
            fixed(byte *pinned = message)
            {
                udp_hdr *udphdr = (udp_hdr *)pinned;

                udphdr->dest = CheckSum.htons((ushort)frame.Destination.Port);
                udphdr->src  = CheckSum.htons((ushort)frame.Source.Port);
                udphdr->len  = CheckSum.htons((ushort)message.Length);

                using (MemoryStream ms = new MemoryStream(message, offset, payload_len))
                {
                    ms.Write(frame.Payload.Buffer, frame.Payload.Offset, payload_len);
                }

                ushort pseudo_checksum = CheckSum.inet_chksum_pseudo(pinned,
                                                                     (uint)ProtocolType.Udp,
                                                                     (uint)message.Length,
                                                                     IPFrame.GetAddressV4(frame.Source.Address),
                                                                     IPFrame.GetAddressV4(frame.Destination.Address));

                if (pseudo_checksum == 0)
                {
                    pseudo_checksum = 0xffff;
                }

                udphdr->chksum = pseudo_checksum;
            }

            return(new IPFrame(ProtocolType.Udp, frame.Source.Address, frame.Destination.Address, new BufferSegment(message))
            {
                Ttl = frame.Ttl,
                SourceMacAddress = frame.SourceMacAddress,
                DestinationMacAddress = frame.DestinationMacAddress,
            });
        }
Ejemplo n.º 2
0
        public void TooManyRegistersInRangeMessage()
        {
            // Arrange
            var buffer = new byte[] { 0xBB, 0x00, 0x0C, 0x00, 0xA5, 0x01, 0x07, 0x03, 0x04, 0x05, 0x06, 0x00 };

            // fill checkSums
            buffer[3] = CheckSum.Crc8(buffer.AsSpan().Slice(0, 3).ToArray());
            buffer[buffer.Length - 1] = CheckSum.Crc8(buffer.AsSpan().Slice(0, buffer.Length - 1).ToArray());
            // Act
            Assert.Throws <TooMuchDataRequestedException>(() => _parser.Parse(buffer));
            // Assert
            Assert.Equal(1, _messageCount);
        }
Ejemplo n.º 3
0
        public void PacketTooLong()
        {
            // Arrange
            var buffer = new byte[] { 0xBB, 0x01, 0x11, 0x00, 0xA5, 0x01, 0x08, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x00 };

            // fill checkSums
            buffer[3] = CheckSum.Crc8(buffer.AsSpan().Slice(0, 3).ToArray());
            buffer[buffer.Length - 1] = CheckSum.Crc8(buffer.AsSpan().Slice(0, buffer.Length - 1).ToArray());
            // Act
            _parser.Parse(buffer);
            // Assert
            Assert.Equal(0, _messageCount);
        }
Ejemplo n.º 4
0
        public void TestMethod2()
        {
            CheckSum checker = new CheckSum();

            string testDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName;

            string result1 = checker.GetCheckSum($@"{testDir}\TestDir");

            SafeCheckSum safeChecker = new SafeCheckSum();
            string       result2     = safeChecker.GetCheckSum($@"{testDir}\TestDir");

            Assert.AreEqual(result2, result1);
        }
Ejemplo n.º 5
0
        public void StartAddressIsGreaterThanEndAddress()
        {
            // Arrange
            var buffer = new byte[] { 0xBB, 0x00, 0x0C, 0x00, 0xA5, 0x04, 0x01, 0x03, 0x04, 0x05, 0x06, 0x00 };

            // fill checkSums
            buffer[3] = CheckSum.Crc8(buffer.AsSpan().Slice(0, 3).ToArray());
            buffer[buffer.Length - 1] = CheckSum.Crc8(buffer.AsSpan().Slice(0, buffer.Length - 1).ToArray());
            // Act
            Assert.Throws <InvalidRegistersException>(() => _parser.Parse(buffer));
            // Assert
            Assert.Equal(1, _messageCount);
        }
Ejemplo n.º 6
0
        public static BufferSegment ToArray(IPFrame frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }
            BufferSegment payload_segment = frame.Payload;
            BufferSegment options_segment = frame.Options;
            int           options_size    = options_segment?.Length ?? 0;
            int           payload_offset  = sizeof(ip_hdr) + options_size;
            int           payload_size    = payload_segment?.Length ?? 0;

            byte[] message_data = new byte[payload_offset + payload_size];
            fixed(byte *pinned = message_data)
            {
                ip_hdr *iphdr = (ip_hdr *)pinned;

                iphdr->dest   = frame.DestinationAddressV4;
                iphdr->src    = frame.SourceAddressV4;
                iphdr->_ttl   = (byte)frame.Ttl;
                iphdr->_proto = (byte)frame.ProtocolType;
                iphdr->_v_hl  = (byte)(4 << 4 | payload_offset >> 2);
                iphdr->_tos   = frame.Tos; // Routine Mode
                iphdr->_len   = CheckSum.htons((ushort)message_data.Length);
                iphdr->_id    = CheckSum.htons(frame.Id);
                iphdr->_flags = CheckSum.ntohs((ushort)frame.Flags);

                if (options_size > 0)
                {
                    IntPtr destination_options = (IntPtr)(pinned + sizeof(ip_hdr));
                    Marshal.Copy(options_segment.Buffer, options_segment.Offset, destination_options, options_size);
                }

                if (payload_size > 0)
                {
                    using (MemoryStream ms = new MemoryStream(message_data, payload_offset, payload_size))
                    {
                        ms.Write(payload_segment.Buffer, payload_segment.Offset, payload_size);
                    }
                }

                iphdr->_chksum = CheckSum.inet_chksum(pinned, payload_offset);
                if (iphdr->_chksum == 0)
                {
                    iphdr->_chksum = 0xffff;
                }
            }

            return(new BufferSegment(message_data));
        }
        private void OpenServer()
        {
            IsConnected   = !IsConnected;
            ConnectStatus = $"연결 {(!IsConnected ? "시작" : "중지")}";
            RaisePropertyChanged(nameof(ConnectStatus));
            if (IsConnected == false)
            {
                receiverSubscription?.Dispose();
                return;
            }
            //serial.
            // using(Serial serial = new Serial())
            //{
            if (senderSubscription != null)
            {
                senderSubscription.Dispose();
            }
            if (receiverSubscription != null)
            {
                receiverSubscription.Dispose();
            }
            var startChar = (0x02).AsObservable();
            var endChar   = (0x03).AsObservable();

            serial.OpenSerial(configuration);
            receiverSubscription = serial
                                   .BufferUntilByte(startChar, endChar, 100)
                                   .Subscribe(v => {
                if (IsOn == false)
                {
                    IsOn = true;
                }
                byte checksum = v[v.Length - 1];
                var data      = v.Skip(1).Take(v.Length - 2).ToArray();
                //var checksum2 = (byte)(data.Aggregate(0,(c, d) => c + d) & 0xFF);
                var Checksum     = new CheckSum();
                var result       = Checksum.GetCheckSum(checksum, data);
                var bytetostring = BitConverter.ToString(v);
                ReceiveTB       += "받은 데이터 : " + bytetostring + " 체크섬 : " + result.Item1 + " bool " + result.Item2 + "  \n";
                if (ReceiveTB.Length >= 3000)
                {
                    ReceiveTB = "받은 데이터 : " + bytetostring + " 체크섬 : " + result.Item1 + " bool " + result.Item2 + "  \n";
                }
                RaisePropertyChanged(nameof(ReceiveTB));
            });

            //serial.RecvDataList
            //blahblah
            //}
        }
Ejemplo n.º 8
0
        public ActionResult CreatePayment(RequestData data)
        {
            String merchantKey = PaytmTest.merchantKey;
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", PaytmTest.merchantId);
            parameters.Add("CHANNEL_ID", "WEB");
            parameters.Add("INDUSTRY_TYPE_ID", "Retail");
            parameters.Add("WEBSITE", "WEBSTAGING");
            parameters.Add("EMAIL", data.Email);
            parameters.Add("MOBILE_NO", data.MobileNumber);
            parameters.Add("CUST_ID", "22");
            parameters.Add("ORDER_ID", "abcdefghijklmnodfdfdsfp");
            parameters.Add("TXN_AMOUNT", data.Amount);
            parameters.Add("CALLBACK_URL", "https://merchant.com/callback/"); //This parameter is not mandatory. Use this to pass the callback url dynamically.

            string checksum = CheckSum.generateCheckSum(merchantKey, parameters);

            string paytmURL = "https://securegw-stage.paytm.in/theia/processTransaction?orderid=" + parameters.FirstOrDefault(x => x.Key == "ORDER_ID").Value;


            string outputHTML = "<html>";

            outputHTML += "<head>";
            outputHTML += "<title>Merchant Check Out Page</title>";
            outputHTML += "</head>";
            outputHTML += "<body>";
            outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
            outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
            outputHTML += "<table border='1'>";
            outputHTML += "<tbody>";
            foreach (string key in parameters.Keys)
            {
                outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
            }
            outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
            outputHTML += "</tbody>";
            outputHTML += "</table>";
            outputHTML += "<script type='text/javascript'>";
            outputHTML += "document.f1.submit();";
            outputHTML += "</script>";
            outputHTML += "</form>";
            outputHTML += "</body>";
            outputHTML += "</html>";
            Response.Write(outputHTML);

            ViewBag.htmldata = outputHTML;

            return(View("PaymentPage"));
        }
Ejemplo n.º 9
0
        String strDBError = "Изменения не сохранены из-за ошибки. Возможно введены повторяющиеся данные."; //текст ошибки

        public EditDBForm(string selectDataGridViesEdit,
                          object[] defaultRowItemArray,
                          int[] required,
                          string command,
                          String[] paramsNames,
                          SqlDbType[] types,
                          bool tag,
                          int idForTags,
                          CheckSum checkSum,
                          bool isReserve)//конструктор
        {
            InitializeComponent();
            this.selectDataGridViesEdit = selectDataGridViesEdit;
            this.defaultRowItemArray    = defaultRowItemArray;
            this.required    = required;
            this.command     = command;
            this.paramsNames = paramsNames;
            this.types       = types;
            this.tag         = tag;
            this.idForTags   = idForTags;
            this.checkSum    = checkSum;
            this.isReserve   = isReserve;

            if (selectDataGridViesEdit != null)//заполнение дгв
            {
                Program.SetDataGridViewDataSource(selectDataGridViesEdit, ref dataGridViewEdit);
                if (defaultRowItemArray != null)
                {
                    ((DataTable)dataGridViewEdit.DataSource).Rows.Add(defaultRowItemArray);
                }

                try { dataGridViewEdit.Columns["Сумма"].DefaultCellStyle.Format = "F"; } catch { }
                this.Width = dataGridViewEdit.ColumnCount * 185;
            }
            else
            {
                HideSelect();
            }


            if (tag)
            {
                UpdateTegs();
            }
            else
            {
                HideTags();
            }
        }
Ejemplo n.º 10
0
        /*[ValidateInput(false)]
         * public ActionResult ReturnOLD(FormCollection form)
         * {
         *  var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.Paytm") as PaytmPaymentProcessor;
         *  if (processor == null ||
         *      !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
         *      throw new NopException("Paytm module cannot be loaded");
         *
         *
         *  var myUtility = new PaytmHelper();
         *              string orderId,  Amount, AuthDesc, ResCode;
         *              bool checkSumMatch = false;
         *              //Assign following values to send it to verifychecksum function.
         *              if (String.IsNullOrWhiteSpace(_PaytmPaymentSettings.MerchantKey))
         *                      throw new NopException("Paytm key is not set");
         *
         *              string workingKey = _PaytmPaymentSettings.MerchantKey;
         *
         *
         *              Dictionary<string, string> parameters = new Dictionary<string, string>();
         *              if (Request.Form.AllKeys.Length > 0)
         *              {
         *
         *                      string paytmChecksum="";
         *                      foreach (string key in Request.Form.Keys){
         *                              parameters.Add(key.Trim(), Request.Form[key].Trim());
         *                      }
         *
         *                      if(parameters.ContainsKey("CHECKSUMHASH")){
         *                              paytmChecksum = parameters["CHECKSUMHASH"];
         *                              parameters.Remove("CHECKSUMHASH");
         *                      }
         *
         *                      if (CheckSum.verifyCheckSum(workingKey, parameters, paytmChecksum))	{
         *                              checkSumMatch = true;
         *
         *                      }
         *
         *              }
         *
         *              orderId = parameters["ORDERID"];
         *              Amount = parameters["TXNAMOUNT"];
         *              ResCode = parameters["RESPCODE"];
         *              AuthDesc = parameters["STATUS"];
         *
         *  if (checkSumMatch == true)
         *  {
         *      if (ResCode == "01" && AuthDesc == "TXN_SUCCESS")
         *      {
         *          var order = _orderService.GetOrderById(Convert.ToInt32(orderId));
         *          if (_orderProcessingService.CanMarkOrderAsPaid(order))
         *          {
         *              _orderProcessingService.MarkOrderAsPaid(order);
         *          }
         *          return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
         *      }
         *      else if (AuthDesc == "TXN_FAILURE")
         *      {
         *          return RedirectToRoute("ShoppingCart");
         *      }
         *      else
         *      {
         *          return Content("Security Error. Illegal access detected");
         *      }
         *  }
         *  else
         *  {
         *      return Content("Security Error. Illegal access detected, Checksum failed");
         *  }
         * }*/

        private bool TxnStatus(string OrderId, String amount)
        {
            String uri = "https://pguat.paytm.com/oltp/HANDLER_INTERNAL/getTxnStatus";

            if (_PaytmPaymentSettings.PaymentUrl.ToLower().Contains("secure.paytm.in"))
            {
                uri = "https://secure.paytm.in/oltp/HANDLER_INTERNAL/getTxnStatus";
            }

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", _PaytmPaymentSettings.MerchantId);
            parameters.Add("ORDERID", OrderId);

            string checksum = CheckSum.generateCheckSum(_PaytmPaymentSettings.MerchantKey, parameters);//.Replace("+", "%2B");

            try
            {
                string postData = "{\"MID\":\"" + _PaytmPaymentSettings.MerchantId + "\",\"ORDERID\":\"" + OrderId + "\",\"CHECKSUMHASH\":\"" + HttpUtility.UrlEncode(checksum) + "\"}";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Method      = "POST";
                webRequest.Accept      = "application/json";
                webRequest.ContentType = "application/json";

                using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter2.Write("JsonData=" + postData);
                }
                string responseData = string.Empty;
                using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
                {
                    responseData = responseReader.ReadToEnd();
                    if (responseData.Contains("TXN_SUCCESS") && responseData.Contains(amount))
                    {
                        return(true);
                    }
                    else
                    {
                        //
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error " + ex.Message);
            }
            return(false);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("\t*****************************");
            Console.WriteLine("\tChecksum Calculation");
            Console.WriteLine("\t*****************************");

            Console.WriteLine("\tPlease enter a NMI.");
            var nmi           = Console.ReadLine();
            var checkSumValue = CheckSum.GetCheckDigit(nmi);

            Console.WriteLine("\t");
            Console.WriteLine("\t*****************************");
            Console.WriteLine($"\tResult is: \t {checkSumValue}");
            Console.WriteLine("\t*****************************");
        }
Ejemplo n.º 12
0
        public void ComposeRange(int firstRegisterAddress, int registerCount, MessageType messageType, OperationType operationType, byte[] expected)
        {
            // Arrange
            // fill checkSums
            expected[3] = CheckSum.Crc8(expected.AsSpan().Slice(0, 3).ToArray());
            expected[expected.Length - 1] = CheckSum.Crc8(expected.AsSpan().Slice(0, expected.Length - 1).ToArray());

            IRegisterMessage message = _messageFactory.CreateRange(firstRegisterAddress, registerCount, operationType, messageType);

            // Act
            byte[] actual = _composer.Compose(message, out IReadOnlyCollection <IRegisterGroup> composedGroups);

            // Assert
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 13
0
    public void paytmpayment(string EMAIL, string MOBILE_NO, string CUST_ID, string ORDER_ID, string TXN_AMOUNT)
    {
        String merchantKey = "rd_&uwtYvTsEoGXZ";
        //String merchantKey = "#8WZV0O&@j6rmhSg";
        Dictionary <string, string> parameters = new Dictionary <string, string>();

        parameters.Add("MID", "keUFsv31297320723737");
        //parameters.Add("MID", "CiyDSy57205844069986");
        parameters.Add("CHANNEL_ID", "WEB");
        parameters.Add("INDUSTRY_TYPE_ID", "Retail");
        parameters.Add("WEBSITE", "WEBSTAGING");
        parameters.Add("EMAIL", EMAIL);
        parameters.Add("MOBILE_NO", MOBILE_NO);
        parameters.Add("CUST_ID", CUST_ID);
        parameters.Add("ORDER_ID", ORDER_ID);
        parameters.Add("TXN_AMOUNT", TXN_AMOUNT);
        parameters.Add("CALLBACK_URL", CALLBACK_URL); //This parameter is not mandatory. Use this to pass the callback url dynamically.

        string checksum = CheckSum.generateCheckSum(merchantKey, parameters);

        string paytmURL = "https://securegw-stage.paytm.in/theia/processTransaction?orderid=" + ORDER_ID;

        string outputHTML = "<html>";

        outputHTML += "<head>";
        outputHTML += "<title>Merchant Check Out Page</title>";
        outputHTML += "</head>";
        outputHTML += "<body>";
        outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
        outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
        outputHTML += "<table border='1'>";
        outputHTML += "<tbody>";
        foreach (string key in parameters.Keys)
        {
            outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
        }
        outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
        outputHTML += "</tbody>";
        outputHTML += "</table>";
        outputHTML += "<script type='text/javascript'>";
        outputHTML += "document.f1.submit();";
        outputHTML += "</script>";
        outputHTML += "</form>";
        outputHTML += "</body>";
        outputHTML += "</html>";
        Response.Write(outputHTML);
    }
Ejemplo n.º 14
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //string amount = postProcessPaymentRequest.Order.OrderTotal.ToString ("#.##");
            //amount.ToString ();
            var remotePostHelper     = new RemotePost();
            var remotePostHelperData = new Dictionary <string, string>();

            remotePostHelper.FormName = "PaytmForm";
            remotePostHelper.Url      = _PaytmPaymentSettings.PaymentUrl;
            remotePostHelperData.Add("MID", _PaytmPaymentSettings.MerchantId.ToString());
            remotePostHelperData.Add("WEBSITE", _PaytmPaymentSettings.Website.ToString());
            remotePostHelperData.Add("CHANNEL_ID", "WEB");
            remotePostHelperData.Add("INDUSTRY_TYPE_ID", _PaytmPaymentSettings.IndustryTypeId.ToString());
            remotePostHelperData.Add("TXN_AMOUNT", postProcessPaymentRequest.Order.OrderTotal.ToString("#.##"));
            remotePostHelperData.Add("ORDER_ID", postProcessPaymentRequest.Order.Id.ToString());
            remotePostHelperData.Add("EMAIL", postProcessPaymentRequest.Order.BillingAddress.Email);
            remotePostHelperData.Add("MOBILE_NO", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber);
            remotePostHelperData.Add("CUST_ID", postProcessPaymentRequest.Order.BillingAddress.Email);
            remotePostHelperData.Add("CALLBACK_URL", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPaytm/Return");

            //remotePostHelperData.Add("CALLBACK_URL", _PaytmPaymentSettings.CallBackUrl.ToString());

            Dictionary <string, string> parameters = new Dictionary <string, string> ();


            foreach (var item in remotePostHelperData)
            {
                parameters.Add(item.Key, item.Value);
                remotePostHelper.Add(item.Key, item.Value);
            }


            try
            {
                string checksumHash = "";

                checksumHash = CheckSum.generateCheckSum(_PaytmPaymentSettings.MerchantKey, parameters);
                remotePostHelper.Add("CHECKSUMHASH", checksumHash);


                remotePostHelper.Post();
            }
            catch (Exception ep)
            {
                throw new Exception(ep.Message);
            }
        }
Ejemplo n.º 15
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(ValidationResult.Success);
            }

            var bulstat = value.ToString();

            if (bulstat != null && (bulstat.Length == this.mass.Length + 1 || bulstat.Length == this.mass.Length + this.massDomain.Length))
            {
                if (int.TryParse(bulstat.Substring(0, 9), out var workData))
                {
                    int res = new CheckSum().CalculateCheckSum(workData, this.mass);
                    if (res == 10)
                    {
                        res = new CheckSum().CalculateCheckSum(workData, this.massExt);
                    }

                    if (res % 10 != workData % 10)
                    {
                        return(new ValidationResult(this.errorMessage));
                    }

                    if (bulstat.Length == 13)
                    {
                        if (int.TryParse(bulstat.Substring(8, 4), out workData))
                        {
                            res = new CheckSum().CalculateCheckSum(workData, this.massDomain);
                            if (res == 10)
                            {
                                res = new CheckSum().CalculateCheckSum(workData, this.massDomainExt);
                            }

                            if (res % 10 != workData % 10)
                            {
                                return(new ValidationResult(this.errorMessage));
                            }
                        }
                    }

                    return(ValidationResult.Success);
                }
            }

            return(new ValidationResult(this.errorMessage));
        }
Ejemplo n.º 16
0
        private void Code39()
        {
            int           index;
            char          checkDigit;
            int           inputLength = barcodeData.Length;
            StringBuilder rowPattern  = new StringBuilder();

            if (inputLength > 74)
            {
                throw new InvalidDataLengthException("Code 39: Input data too long.");
            }

            for (int i = 0; i < inputLength; i++)
            {
                if (CharacterSets.Code39Set.IndexOf(barcodeData[i]) == -1)
                {
                    throw new InvalidDataException("Code 39: Invalid characters in input data.");
                }
            }

            rowPattern.Append(Code39Table[43]);
            for (int i = 0; i < inputLength; i++)
            {
                index = CharacterSets.Code39Set.IndexOf(barcodeData[i]);
                rowPattern.Append(Code39Table[index]);
            }

            if (optionalCheckDigit)
            {
                checkDigit = CheckSum.Mod43CheckDigit(barcodeData);
                index      = CharacterSets.Code39Set.IndexOf(checkDigit);
                rowPattern.Append(Code39Table[index]);
                checkDigitText = checkDigit.ToString();
            }

            rowPattern.Append(Code39Table[43]);

            if (symbolId == Symbology.LOGMARS || encodingMode == EncodingMode.HIBC)
            {
                rowPattern.Replace('2', '3');
            }

            barcodeText = barcodeMessage;

            // Expand the row pattern into the symbol data.
            SymbolBuilder.ExpandSymbolRow(Symbol, rowPattern, 0.0f);
        }
Ejemplo n.º 17
0
        protected void PaytmPayment(object sender, EventArgs e)
        {
            string emailId      = ((TextBox)FindControl("txtEmail")).Text;
            string mobileNumber = ((TextBox)FindControl("txtMobileNumber")).Text;
            String merchantKey  = "3nq9CVSw2mPNqs6o";
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", "lEGUpY97255671347258");
            parameters.Add("CHANNEL_ID", "WEB");
            parameters.Add("INDUSTRY_TYPE_ID", "Retail");
            parameters.Add("WEBSITE", "WEBSTAGING");
            parameters.Add("EMAIL", emailId);
            parameters.Add("MOBILE_NO", mobileNumber);
            parameters.Add("CUST_ID", "Cust01");
            parameters.Add("ORDER_ID", "OR06");
            parameters.Add("TXN_AMOUNT", "200");
            parameters.Add("CALLBACK_URL", "http://localhost:6042/Response.aspx");

            string checksum = CheckSum.generateCheckSum(merchantKey, parameters);

            string paytmURL = "https://securegw-stage.paytm.in/theia/processTransaction?orderid=OR01";

            string outputHTML = "<html>";

            outputHTML += "<head>";
            outputHTML += "<title>Merchant Check Out Page</title>";
            outputHTML += "</head>";
            outputHTML += "<body>";
            outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
            outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
            outputHTML += "<table border='1'>";
            outputHTML += "<tbody>";
            foreach (string key in parameters.Keys)
            {
                outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
            }
            outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
            outputHTML += "</tbody>";
            outputHTML += "</table>";
            outputHTML += "<script type='text/javascript'>";
            outputHTML += "document.f1.submit();";
            outputHTML += "</script>";
            outputHTML += "</form>";
            outputHTML += "</body>";
            outputHTML += "</html>";
            Response.Write(outputHTML);
        }
Ejemplo n.º 18
0
        public void PaytmPay(string EMAIL, string MOBILE_NO, string CUST_ID, string ORDER_ID, string TXN_AMOUNT, string CALLBACK_URL)
        {
            String merchantKey = "xw5xw0o97g2nwG5z";
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", "shopps11631241477240");
            parameters.Add("CHANNEL_ID", "WEB");
            parameters.Add("INDUSTRY_TYPE_ID", "Retail");
            parameters.Add("WEBSITE", "WEB_STAGING");
            parameters.Add("EMAIL", EMAIL);
            parameters.Add("MOBILE_NO", MOBILE_NO);
            parameters.Add("CUST_ID", CUST_ID);
            parameters.Add("ORDER_ID", ORDER_ID);
            parameters.Add("TXN_AMOUNT", TXN_AMOUNT);
            parameters.Add("CALLBACK_URL", CALLBACK_URL);

            //This parameter is not mandatory. Use this to pass the callback url dynamically.

            string checksum = CheckSum.generateCheckSum(merchantKey, parameters);

            string paytmURL = "https://pguat.paytm.com/oltp-web/processTransaction?orderid=" + ORDER_ID;

            string outputHTML = "<html>";

            outputHTML += "<head>";
            outputHTML += "<title>Merchant Check Out Page</title>";
            outputHTML += "</head>";
            outputHTML += "<body>";
            outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
            outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
            outputHTML += "<table border='1'>";
            outputHTML += "<tbody>";
            foreach (string key in parameters.Keys)
            {
                outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
            }
            outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
            outputHTML += "</tbody>";
            outputHTML += "</table>";
            outputHTML += "<script type='text/javascript'>";
            outputHTML += "document.f1.submit();";
            outputHTML += "</script>";
            outputHTML += "</form>";
            outputHTML += "</body>";
            outputHTML += "</html>";
            Response.Write(outputHTML);
        }
Ejemplo n.º 19
0
        public static string Generate(string errorCode)
        {
            StringBuilder ret = new StringBuilder();

            ret.Append($",{errorCode}");

            if (AppConfiguration.checkSumCheck)
            {
                var chksum = CheckSum.Compute(ret.ToString());
                ret.Append(',');
                ret.Append(chksum);
            }

            ret.Append('\r');
            ret.Insert(0, '?');
            return(ret.ToString());
        }
Ejemplo n.º 20
0
        public static void Refund_PayTm_Order(string pOrderId,
                                              string pTxnId,
                                              string pRefundAmount,
                                              string pComments,
                                              string pReferenceId)
        {
            PayTmConfiguration lPayTmConfiguration = PaymentClass.Get_Paytm_Configuration();
            PayTmPaymentGatewayRefundRequest lPaymentGatewayRefundRequest = new PayTmPaymentGatewayRefundRequest();
            Dictionary <string, string>      parameters = new Dictionary <string, string>();

            lPaymentGatewayRefundRequest.MID          = lPayTmConfiguration.MID;
            lPaymentGatewayRefundRequest.TXNID        = pTxnId;
            lPaymentGatewayRefundRequest.ORDERID      = pOrderId;
            lPaymentGatewayRefundRequest.REFUNDAMOUNT = pRefundAmount;
            lPaymentGatewayRefundRequest.TXNTYPE      = "REFUND";
            lPaymentGatewayRefundRequest.COMMENTS     = pComments;
            lPaymentGatewayRefundRequest.REFID        = pReferenceId;
            parameters.Add("MID", lPayTmConfiguration.MID);
            parameters.Add("TXNID", pTxnId);
            parameters.Add("ORDERID", pOrderId);
            parameters.Add("REFUNDAMOUNT", pRefundAmount);
            parameters.Add("TXNTYPE", "REFUND");
            parameters.Add("COMMENTS", pComments);
            parameters.Add("REFID", pReferenceId);

            string checksum = CheckSum.generateCheckSum(lPayTmConfiguration.Merchant_Key, parameters);

            lPaymentGatewayRefundRequest.CHECKSUM = checksum;

            JavaScriptSerializer lJavaScriptSerializer = new JavaScriptSerializer();
            var lJson = lJavaScriptSerializer.Serialize(lPaymentGatewayRefundRequest);

            WebRequest      lWebRequest         = WebRequest.Create(lPayTmConfiguration.Refund_Url + "?JsonData=" + lJson);
            HttpWebResponse lHttpWebResponse    = (HttpWebResponse)lWebRequest.GetResponse();
            Stream          lStream             = lHttpWebResponse.GetResponseStream();
            StreamReader    lStreamReader       = new StreamReader(lStream);
            string          lResponseFromSender = lStreamReader.ReadToEnd();

            //    PaymentGatewayResponse lPaymentGatewayResponse = lJavaScriptSerializer.Deserialize<PaymentGatewayResponse>(lResponseFromSender);
            lStreamReader.Close();
            lStream.Close();
            lHttpWebResponse.Close();

            //    if (lPaymentGatewayResponse != null)
            //    {
        }
        public void PaytmGateway()
        {
            var    rnd         = new Random();
            string merchantKey = "cGb1WUa9umc6ds0#";
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", "qRhfGq94735000540451");
            parameters.Add("CHANNEL_ID", "WEB");
            parameters.Add("INDUSTRY_TYPE_ID", "Retail");
            parameters.Add("WEBSITE", "WEBSTAGING");
            parameters.Add("EMAIL", "*****@*****.**");
            parameters.Add("MOBILE_NO", "9717245991");
            parameters.Add("CUST_ID", "cust1");
            parameters.Add("ORDER_ID", rnd.Next(1, 999999).ToString());
            parameters.Add("TXN_AMOUNT", rnd.Next(99, 999).ToString());
            parameters.Add("CALLBACK_URL", "https://localhost:44380/Home/ordercompletion");

            string checksum = CheckSum.generateCheckSum(merchantKey, parameters);

            string paytmURL = "https://securegw-stage.paytm.in/theia/processTransaction";

            string outputHTML = "<html>";

            outputHTML += "<head>";
            outputHTML += "<title>Merchant Check Out Page</title>";
            outputHTML += "</head>";
            outputHTML += "<body>";
            outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
            outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
            outputHTML += "<table border='1'>";
            outputHTML += "<tbody>";
            foreach (string key in parameters.Keys)
            {
                outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
            }
            outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
            outputHTML += "</tbody>";
            outputHTML += "</table>";
            outputHTML += "<script type='text/javascript'>";
            outputHTML += "document.f1.submit();";
            outputHTML += "</script>";
            outputHTML += "</form>";
            outputHTML += "</body>";
            outputHTML += "</html>";
            Response.Write(outputHTML);
        }
        public void CheckSumTest()
        {
            var checkSumValue = CheckSum.CreateCheckSum(new CardChargeParams(TestConsts.recurringPbKey, "Okezie",
                                                                             "Okpara", "*****@*****.**",
                                                                             4556.000m)
            {
                CardNo      = "5438898014560229",
                Cvv         = "789",
                Expirymonth = "09",
                Expiryyear  = "19",
                TxRef       = TestConsts.tranxRef
            }, TestConsts.recurringScKey);

            Trace.WriteLine(checkSumValue);

            Assert.IsNotNull(checkSumValue);
        }
Ejemplo n.º 23
0
        public ActionResult checkCheksum()
        {
            String paytmChecksum = "";

            /* Create a Dictionary from the parameters received in POST */
            Dictionary <String, String> paytmParams = new Dictionary <String, String>();

            foreach (string key in Request.Form.Keys)
            {
                if (key.Equals("CHECKSUMHASH"))
                {
                    paytmChecksum = Request.Form[key];
                }
                else
                {
                    paytmParams.Add(key.Trim(), Request.Form[key].ToString().Trim());
                }
            }

            /**
             * Verify checksum
             * Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
             */
            bool isValidChecksum = CheckSum.verifyCheckSum(Test_Merchant_Key, paytmParams, paytmChecksum);

            if (isValidChecksum)
            {
                Payment pt = new Payment();
                pt.Id = Convert.ToInt64(paytmParams["ORDERID"]
                                        );
                pt = _context.Payments.Find(pt.Id);

                pt.PAYMENTMODE = paytmParams["RESPMSG"];
                pt.RESPCODE    = paytmParams["RESPCODE"];
                //pt.TXNID = Convert.ToInt64(paytmParams["TXNID"]);
                pt.Sataus = paytmParams["STATUS"];


                _context.Payments.Update(pt);

                _context.SaveChanges();
                return(RedirectToAction("index", "home"));
            }

            return(RedirectToAction("index", "home"));
        }
Ejemplo n.º 24
0
        public CheckSum ComputeCheckSum(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            byte[] hash;
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                hash = md5.ComputeHash(stream);
            }

            var checkSum = new CheckSum(hash);

            return(checkSum);
        }
Ejemplo n.º 25
0
        public void paytm_payment()
        {
            String merchantKey = "FxTPSZgXhhwsVXhd";
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("MID", "eLYJEc27730646912112");
            parameters.Add("CHANNEL_ID", "WEB");
            parameters.Add("INDUSTRY_TYPE_ID", "Retail");
            parameters.Add("WEBSITE", "WEBSTAGING");
            parameters.Add("EMAIL", "*****@*****.**");
            parameters.Add("MOBILE_NO", "7054036620");
            parameters.Add("CUST_ID", "123");
            parameters.Add("ORDER_ID", "311");
            parameters.Add("TXN_AMOUNT", "234");
//parameters.Add("CALLBACK_URL", "url"); //This parameter is not mandatory. Use this to pass the callback url dynamically.

            string checksum = CheckSum.generateCheckSum(merchantKey, parameters);
            string paytmURL = "https://securegw-stage.paytm.in/theia/processTransaction?orderid=" + "311";



            string outputHTML = "<html>";

            outputHTML += "<head>";
            outputHTML += "<title>Merchant Check Out Page</title>";
            outputHTML += "</head>";
            outputHTML += "<body>";
            outputHTML += "<center><h1>Please do not refresh this page...</h1></center>";
            outputHTML += "<form method='post' action='" + paytmURL + "' name='f1'>";
            outputHTML += "<table border='1'>";
            outputHTML += "<tbody>";
            foreach (string key in parameters.Keys)
            {
                outputHTML += "<input type='hidden' name='" + key + "' value='" + parameters[key] + "'>";
            }
            outputHTML += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>";
            outputHTML += "</tbody>";
            outputHTML += "</table>";
            outputHTML += "<script type='text/javascript'>";
            outputHTML += "document.f1.submit();";
            outputHTML += "</script>";
            outputHTML += "</form>";
            outputHTML += "</body>";
            outputHTML += "</html>";
            Response.Write(outputHTML);
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> Uploading(IFormFile file)
        {
            string fullPath    = "";
            int    folderCount = Track.level;

            //store the file
            FileMaster duplicateFiles = await _context.Files.Include(p => p.FileIterations).FirstOrDefaultAsync(p => p.FileName == file.FileName);

            //Folder getLastFolder = await _context.Folders.LastOrDefaultAsync();
            //Folder parentFolder = await _context.Folders.FirstOrDefaultAsync(p => p.Id == getLastFolder.Id);

            if (duplicateFiles != null)
            {
                string dupliPath = root + duplicateFiles.Location + "/" + duplicateFiles.FileName;
                fullPath = FormatthePath(dupliPath);
            }

            if (file.Length > 0)
            {
                if (duplicateFiles == null)
                {
                    return(new ObjectResult(await upNewFile(file)));
                }
                else
                {
                    Stream   stream   = file.OpenReadStream();
                    CheckSum checkSum = new CheckSum();

                    if (duplicateFiles.FileIterations.Any(f => f.IterationCheckSum == checkSum.CalcCRC32(stream)))
                    {
                        return(new ObjectResult("Same file already exists!"));
                    }
                    else
                    {
                        FileMaster fi = await updateFile(stream, checkSum, file, duplicateFiles, fullPath);

                        return(Ok());
                    }
                }
            }
            else
            {
                return(new ObjectResult("Empty file Choosen!"));
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Testing run time.
        /// </summary>
        /// <param name="path">Path</param>
        private bool RunningTimeTesting(string path)
        {
            var checkSum = new CheckSum();

            var stopWathSingleThreaded = new Stopwatch();

            stopWathSingleThreaded.Start();
            checkSum.SingleThreaded(path);
            stopWathSingleThreaded.Stop();

            var stopWathMultipleThreaded = new Stopwatch();

            stopWathMultipleThreaded.Start();
            checkSum.SingleThreaded(path);
            stopWathMultipleThreaded.Stop();

            return(stopWathMultipleThreaded.Elapsed > stopWathSingleThreaded.Elapsed ? true : false);
        }
Ejemplo n.º 28
0
        //public BaseEvent()
        //{
        //    _builder = new StringBuilder();
        //}
        public virtual string Generate(int device, string errorCode, string result = null)
        {
            var date = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss,");

            _builder.Insert(4, date);
            _builder.Insert(0, $",{device},EVNT,");

            if (AppConfiguration.checkSumCheck)
            {
                var chksum = CheckSum.Compute(_builder.ToString());
                _builder.Append(',');
                _builder.Append(chksum);
            }

            _builder.Append('\r');
            _builder.Insert(0, '>');
            return(_builder.ToString());
        }
    static void Main()
    {
        Console.WriteLine("\n\n\n\n#######-------Executing Assignment 1-------#######");
        //executing ques1
        CheckSum obj1 = new CheckSum();

        obj1.Execute();

        //executing ques2
        TeamPoint obj2 = new TeamPoint();

        obj2.Execute();

        //executing ques3
        GetFirstLetterWord obj3 = new GetFirstLetterWord();

        obj3.Execute();
    }
Ejemplo n.º 30
0
        public void ParseErrorMessage(byte[] buffer)
        {
            // Arrange
            // fill checkSums
            buffer[3] = CheckSum.Crc8(buffer.AsSpan().Slice(0, 3).ToArray());
            buffer[buffer.Length - 1] = CheckSum.Crc8(buffer.AsSpan().Slice(0, buffer.Length - 1).ToArray());
            // Act
            _parser.Parse(buffer);
            // Asserts
            Assert.Equal(1, _messageCount);
            var milliGanjubusMessage = _parsedMessage as MilliGanjubusErrorMessage;

            Assert.NotNull(milliGanjubusMessage);
            Assert.Equal(_parsedMessage.SlaveDeviceAddress, buffer[1]);
            // Assert errorType
            Assert.NotNull(milliGanjubusMessage);
            Assert.Equal(buffer[5], milliGanjubusMessage.ErrorCode);
        }
Ejemplo n.º 31
0
        private CheckSum findFWChecksum(FileStream a_fileStream, int areaStart)
        {
            logger.Debug("findFWChecksum with areaStart: " + areaStart.ToString("X8"));
             byte[] data = new byte[4];
             byte areaNumber = 0;
             int baseAddr = 0;
             int ltemp = 0;
             int csumAddr = 0;
             short csumLength = 0;
             CheckSum r_checkSum = new CheckSum();
             //if (areaStart > 0x7FFFF) areaStart = areaStart - m_sramOffset;
             if (areaStart > 0x7FFFF)
             {
                 r_checkSum.checksumAddress = -1;
                 r_checkSum.checksumValue = -1;
                 return r_checkSum;
             }

             a_fileStream.Position = (areaStart + 22);

             while( a_fileStream.Position < 0x7FFFF )
             {
                    data[0] = (byte)a_fileStream.ReadByte();
                    data[1] = (byte)a_fileStream.ReadByte();
                    if( data[0] == 0x48 )
                    {
                        switch( data[1] )
                        {
                            case 0x6D:
                                data[0] = (byte)a_fileStream.ReadByte();
                                data[1] = (byte)a_fileStream.ReadByte();
                                csumAddr = baseAddr + (int)(data[0] << 8 | data[1]);
                                csumArea[areaNumber].addr = csumAddr;
                                areaNumber++;
                                break;
                            case 0x78:
                                data[0] = (byte)a_fileStream.ReadByte();
                                data[1] = (byte)a_fileStream.ReadByte();
                                csumLength = (short)(data[0] << 8 | data[1]);
                                csumArea[areaNumber].length = csumLength;
                                break;
                            case 0x79:
                                data[0] = (byte)a_fileStream.ReadByte();
                                data[1] = (byte)a_fileStream.ReadByte();
                                data[2] = (byte)a_fileStream.ReadByte();
                                data[3] = (byte)a_fileStream.ReadByte();
                                csumAddr = (int)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]);
                                csumArea[areaNumber].addr = csumAddr;
                                areaNumber++;
                                break;
                            default:
                                break;
                        }
                    }
                    else if( data[0] == 0x2A && data[1] == 0x7C )
                    {
                        data[0] = (byte)a_fileStream.ReadByte();
                        data[1] = (byte)a_fileStream.ReadByte();
                        data[2] = (byte)a_fileStream.ReadByte();
                        data[3] = (byte)a_fileStream.ReadByte();
                        ltemp = (int)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]);
                        /*if (ltemp > 0xF00000L)
                        {
                            ltemp = ltemp - m_sramOffset;
                        }*/
                        if( ltemp < 0xF00000L )
                        {
                            baseAddr = ltemp;
                        }
                    }
                    else if( data[0] == 0xB0 && data[1] == 0xB9 )
                    {
                        data[0] = (byte)a_fileStream.ReadByte();
                        data[1] = (byte)a_fileStream.ReadByte();
                        data[2] = (byte)a_fileStream.ReadByte();
                        data[3] = (byte)a_fileStream.ReadByte();
                        csumAddr = (int)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]);
                        r_checkSum.checksumAddress = csumAddr;

                        long tmpPos = a_fileStream.Position;
                        a_fileStream.Position = r_checkSum.checksumAddress;
                        data[0] = (byte)a_fileStream.ReadByte();
                        data[1] = (byte)a_fileStream.ReadByte();
                        data[2] = (byte)a_fileStream.ReadByte();
                        data[3] = (byte)a_fileStream.ReadByte();
                        a_fileStream.Position = tmpPos;
                        r_checkSum.checksumValue = (int)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]);

                        break;
                    }
             }
             return r_checkSum;
        }