public void Subscriber()
        {
            Task.Factory.StartNew(() =>
            {
                //	int i = 1;
                while (true)
                {
                    byte[] buffer  = new byte[1024];
                    string MsgT    = SubData.Receive(Encoding.Unicode);
                    int bufferSize = SubData.Receive(buffer);
                    buffer         = buffer.Skip(0).Take(bufferSize).ToArray();
                    Console.WriteLine(MsgT);
                    if (bufferSize > 0)
                    {
                        //Add rawdeserialize here after unpacking send data using invoke written below
                        // this.OnDataArrived.Invoke()

                        FinalPrice FP = (FinalPrice)DataPacket.RawDeserialize(buffer, typeof(FinalPrice));
                        Holder.holderData.TryAdd(FP.Token, FP);
                        OnDataUpdate.Raise(OnDataUpdate, OnDataUpdate.CreateReadOnlyArgs(FP));
                    }
                }
            }
                                  );
        }
Esempio n. 2
0
 protected Order(Guid customerId, Guid basketId, FinalPrice finalPrice, DateTime orderDate)
 {
     CustomerId = customerId;
     BasketId   = basketId;
     FinalPrice = finalPrice;
     OrderDate  = orderDate;
 }
        internal void UDPReciever()
        {
            try
            {
                timerforchecklogin          = new System.Timers.Timer();
                timerforchecklogin.Interval = 30000;
                timerforchecklogin.Start();
                timerforchecklogin.Elapsed += timerforchecklogin_Elapsed;
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        //		string address = subscriber.Receive (Encoding.Unicode);
                        //	    byte[] buffer = new byte[512];
                        //	    int bufferSize = subscriber.Receive (buffer);

                        var buffer = subscriber.Receive();
                        if (buffer == null)
                        {
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("STOP"));
                            continue;
                        }
                        FinalPrice _obj = (FinalPrice)DataPacket.RawDeserialize(buffer.Skip(4).Take(buffer.Length - 4).ToArray(), typeof(FinalPrice));

                        //			Console.WriteLine("Received");
                        //		if(_obj.Token==37454)
                        //			Console.Title="Token: "+_obj.Token+", Bid: "+_obj.MAXBID+", Ask: "+_obj.MINASK+" LTP: "+_obj.LTP;
                        //		else// if (_obj.Token==66039)
                        //		Console.WriteLine("Token {0} Bid {1} Ask {2} LTP {3}",_obj.Token,_obj.MAXBID,_obj.MINASK,_obj.LTP);

                        if (_obj.Token == 111)
                        {
                            Console.WriteLine(" SomeThing Wrong in DATA Server");
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("START"));
                            //	OnDataError.Invoke();
                            continue;
                        }

                        if (_iSubscribe.Contains(_obj.Token))
                        {
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("START"));
                            OnDataArrived.Raise(OnDataArrived, OnDataArrived.CreateReadOnlyArgs(_obj));
                        }
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("Cancellation invoked");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Some unexpected exception ");
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception Raised " + Ex.StackTrace);
            }
        }
        public ActionResult Index(SourceDestination sourceDestination)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            FinalPrice ratesList = GetRates(sourceDestination);

            return(View("Price", ratesList));
        }
Esempio n. 5
0
        public FinalPrice GetTotalPrice()
        {
            FinalPrice totalAmount = 0;

            foreach (var item in Items)
            {
                totalAmount += item.Price;
            }

            return(totalAmount);
        }
Esempio n. 6
0
 public void Save()
 {
     using (var document = DocX.Create(@"table.docx"))
     {
         document.PageLayout.Orientation = Orientation.Landscape;
         var table = document.AddTable(1, 2);
         table.Rows[0].Cells[0].Paragraphs.First().Append(FinalPrice.ToString());
         table.Rows[0].Cells[1].Paragraphs.First().Append(ChildPrice.ToString());
         document.InsertTable(table);
         document.Save();
     }
 }
Esempio n. 7
0
        internal void UDPReciever()
        {
            try
            {
                timerforchecklogin          = new System.Timers.Timer();
                timerforchecklogin.Interval = 30000;
                timerforchecklogin.Start();
                timerforchecklogin.Elapsed += timerforchecklogin_Elapsed;
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        //		string address = subscriber.Receive (Encoding.Unicode);
                        //	    byte[] buffer = new byte[512];
                        //	    int bufferSize = subscriber.Receive (buffer);

                        var buffer = subscriber.Receive();
                        if (buffer == null)
                        {
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("STOP"));
                            continue;
                        }
                        FinalPrice _obj = (FinalPrice)DataPacket.RawDeserialize(buffer.Skip(4).Take(buffer.Length - 4).ToArray(), typeof(FinalPrice));

                        if (_obj.Token == 111)
                        {
                            Console.WriteLine(" SomeThing Wrong in DATA Server");
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("START"));
                            //	OnDataError.Invoke();
                            continue;
                        }

                        if (_iSubscribe.Contains(_obj.Token))
                        {
                            UDP_RecieverData.Instance.TokenData.AddOrUpdate(_obj.Token, _obj, (k, v) => _obj);
                        }
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("Cancellation invoked");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Some unexpected exception ");
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception Raised " + Ex.StackTrace);
            }
        }
        // GET: Price
        public ActionResult Price(FinalPrice ratesList)
        {
            if (ratesList.RatesList == null)
            {
                return(RedirectToAction("Index"));
            }

            if (ratesList.RatesList.Count() < 0)
            {
                return(RedirectToAction("Index"));
            }

            return(View(ratesList));
        }
        public TransactionControl(Order temp)
        {
            InitializeComponent();
            //set the necessary order properties
            FinalPrice  = Math.Round((temp.Subtotal += temp.Subtotal * .16), 2);
            items       = temp.Items;
            OrderNumber = temp.OrderNumber;
            Subtotal    = temp.Subtotal;

            //GetSubtotal();
            FinalPriceDisp.Text = FinalPrice.ToString();
            //the buttons on the form:
            CancelTransaction.Click += OnCancelTransaction;
            PayByCash.Click         += OnPayByCash;
            PayByCredit.Click       += OnPayByCredit;
        }
Esempio n. 10
0
        public void SIGN_ON_REQUEST_OUT(byte[] buffer)  //--2301
        {
			lock(_oblock)
			{
            byte[] buf = { };
            buffer = buffer.Skip(26).ToArray();
            //IPAddress.HostToNetworkOrder (BitConverter.ToInt16 (buffer, 0))

            if (buffer.Length != 40)
            {
                var _checkval = (MS_SYSTEM_INFO_REQ)DataPacket.RawDeserialize(buffer, typeof(MS_SYSTEM_INFO_REQ));



                int trcode = IPAddress.NetworkToHostOrder(_checkval.header_obj.TransactionCode);

                switch (trcode)
                {
                    case 2300:
                        MS_SIGNON obj = (MS_SIGNON)DataPacket.RawDeserialize(buffer, typeof(MS_SIGNON));
                        obj.header_obj.TransactionCode = IPAddress.NetworkToHostOrder((short)2301);
                        obj.header_obj.ErrorCode = IPAddress.NetworkToHostOrder((short)0);
                        obj.BrokerStatus = Convert.ToByte('A');
                        obj.MemberType = IPAddress.NetworkToHostOrder((short)2);
                        obj.ClearingStatus = Convert.ToByte('A');
                        buf = Logic.Instance.GetPF(DataPacket.RawSerialize(obj));
                        sendbuffer(buf);
                        break;
                    case 1600:
                        MS_SYSTEM_INFO_REQ obj1 = (MS_SYSTEM_INFO_REQ)DataPacket.RawDeserialize(buffer, typeof(MS_SYSTEM_INFO_REQ));
                        MS_SYSTEM_INFO_DATA objdata = new MS_SYSTEM_INFO_DATA();
                        objdata.SolicitorPeriod = IPAddress.NetworkToHostOrder((short)0);
                        objdata.header_obj.AlphaChar = obj1.header_obj.AlphaChar;
                        objdata.header_obj.TransactionCode = IPAddress.NetworkToHostOrder((short)1601);
                        objdata.header_obj.TimeStamp1 = obj1.header_obj.TimeStamp1;
                        objdata.header_obj.TimeStamp2 = obj1.header_obj.TimeStamp2;
                        objdata.header_obj.Timestamp = obj1.header_obj.Timestamp;
                        objdata.header_obj.ErrorCode = obj1.header_obj.ErrorCode;
                        objdata.header_obj.LogTime = obj1.header_obj.LogTime;
                        objdata.header_obj.MessageLength = obj1.header_obj.MessageLength;
                        objdata.header_obj.TraderId = obj1.header_obj.TraderId;
                        objdata.st_obj.Normal = IPAddress.NetworkToHostOrder((short)0);
                        objdata.st_ex_obj.Normal = IPAddress.NetworkToHostOrder((short)0);
                        objdata.st_pl_obj.Normal = IPAddress.NetworkToHostOrder((short)0);
                        objdata.UpdatePortfolio = Convert.ToByte('a');
                        objdata.MarketIndex = 0;
                        objdata.DefaultSettlementPeriod_normal = IPAddress.NetworkToHostOrder((short)0);
                        objdata.DefaultSettlementPeriod_spot = IPAddress.NetworkToHostOrder((short)0);
                        objdata.DefaultSettlementPeriod_auction = IPAddress.NetworkToHostOrder((short)0);
                        objdata.CompetitorPeriod = IPAddress.NetworkToHostOrder((short)0);
                        objdata.SolicitorPeriod = IPAddress.NetworkToHostOrder((short)0);
                        objdata.WarningPercent = IPAddress.NetworkToHostOrder((short)0);
                        objdata.VolumeFreezePercent = IPAddress.NetworkToHostOrder((short)0);
                        objdata.SnapQuoteTime = IPAddress.NetworkToHostOrder((short)0);
                        objdata.Reserved1 = IPAddress.NetworkToHostOrder((short)0);
                        objdata.BoardLotQuantity = IPAddress.NetworkToHostOrder(0);
                        objdata.TickSize = IPAddress.NetworkToHostOrder(0);
                        objdata.MaximumGtcDays = IPAddress.NetworkToHostOrder((short)0);
                        objdata.st_stoc_obj.Reserved = Convert.ToByte('r');
                        objdata.st_stoc_obj.Reserved2 = Convert.ToByte('r');
                        objdata.DisclosedQuantityPercentAllowed = IPAddress.NetworkToHostOrder((short)0);
                        objdata.RiskFreeInterestRate = IPAddress.NetworkToHostOrder((short)0);
                        buf = Logic.Instance.GetPF(DataPacket.RawSerialize(objdata));
                        int lth = buf.Length;
                        sendbuffer(buf);
                        break;
				case 20000:
						var obj_1 = (MS_OE_REQUEST_TR)DataPacket.RawDeserialize (buffer, typeof(MS_OE_REQUEST_TR));
					//UDP_Reciever.Instance.Subscribe = IPAddress.NetworkToHostOrder (obj_1.TokenNo);
					Console.WriteLine ("**********************************************************************\n\n\n\n");
					Console.WriteLine (" TransactionCode recieved  \t" + trcode + "\t buffer.Length " + buffer.Length + "\t Buy_SellIndicator = " + IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator) + "\tTokenNo=" + IPAddress.HostToNetworkOrder (obj_1.TokenNo)+" Price :"+IPAddress.HostToNetworkOrder(obj_1.Price));
					Console.WriteLine ("**********************************************************************\n\n\n\n");

					UDP_RecieverData.Instance.Subscribe = IPAddress.HostToNetworkOrder (obj_1.TokenNo);
					var obj_2 = new MS_OE_RESPONSE_TR {
						TransactionCode = IPAddress.NetworkToHostOrder ((short)20073),
						ReasonCode = IPAddress.NetworkToHostOrder ((short)0),
						BookType = IPAddress.NetworkToHostOrder ((short)1),
						GoodTillDate = IPAddress.NetworkToHostOrder (0),
						st_ord_flg_obj = new ST_ORDER_FLAGS {
							STOrderFlagIn = GetBitsToByteValue (0, 0, 0, 1, 0, 0, 0, 0),
							STOrderFlagOut = GetBitsToByteValue (0, 0, 0, 0, 0, 0, 0, 0),
						},
						obj_add_order_flg = new ADDITIONAL_ORDER_FLAGS {
							Reserved1 = 2
						},
						TokenNo = obj_1.TokenNo,
						Contr_dec_tr_Obj = {
							InstrumentName = obj_1.Contr_dec_tr_Obj.InstrumentName,
							Symbol = obj_1.Contr_dec_tr_Obj.Symbol,
							ExpiryDate = obj_1.Contr_dec_tr_Obj.ExpiryDate,
							StrikePrice = obj_1.Contr_dec_tr_Obj.StrikePrice,
							OptionType = obj_1.Contr_dec_tr_Obj.OptionType
						},
						AccountNumber = obj_1.AccountNumber,
						Buy_SellIndicator = obj_1.Buy_SellIndicator,
						DisclosedVolume = obj_1.DisclosedVolume,
						Volume = obj_1.Volume,//IPAddress.NetworkToHostOrder(obj_1), //obj_1.Volume,
						Price = obj_1.Price,
						Open_Close = obj_1.Open_Close,
						UserId = obj_1.UserId, //IPAddress.NetworkToHostOrder (30072),
						BranchId = IPAddress.NetworkToHostOrder ((short)4),
						TraderId = obj_1.UserId, //IPAddress.NetworkToHostOrder (30072),
						BrokerId = Encoding.ASCII.GetBytes ("12468"),
						Settlor = Encoding.ASCII.GetBytes ("".ToUpper ().PadRight (12)),
						Pro_ClientIndicator = IPAddress.NetworkToHostOrder ((short)2),
						nnffield = obj_1.nnffield,

					};
					Console.WriteLine ("20000 Volume"+IPAddress.HostToNetworkOrder(obj_2.Volume));
					obj_2.Pro_ClientIndicator = IPAddress.NetworkToHostOrder ((short)2);
					count += 1;
					obj_2.OrderNumber = DoubleEndianChange (Convert.ToInt64 (DateTime.Now.ToString ("HHmmssfff")) + count);
					//  obj_2.OrderNumber =(long) DoubleEndianChange( 1100100258 + count);
					//Console.WriteLine(" Buy_SellIndicator  "+IPAddress.HostToNetworkOrder(obj_2.Buy_SellIndicator));
					concurrent.TryAdd ((long)1100100258 + count, obj_2);
					sendbuffer (Logic.Instance.GetPF (DataPacket.RawSerialize (obj_2)));
					if (!UDP_RecieverData.Instance.TokenData.ContainsKey (IPAddress.HostToNetworkOrder (obj_1.TokenNo))) {
						UDP_RecieverData.Instance.TokenData [IPAddress.HostToNetworkOrder (obj_1.TokenNo)] = new FinalPrice ();
					}
						FinalPrice _objFinal=new FinalPrice();
					if (UDP_RecieverData.Instance.TokenData.ContainsKey (IPAddress.HostToNetworkOrder (obj_1.TokenNo))) {
							
						_objFinal = UDP_RecieverData.Instance.TokenData [IPAddress.HostToNetworkOrder (obj_1.TokenNo)];
					}
					if (IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator) == 1 && IPAddress.HostToNetworkOrder (obj_1.Price) == 0)
					{
						Console.WriteLine (" 20000 Client Price  0:"+IPAddress.HostToNetworkOrder (obj_1.Price)
								+" Market Bid Price "+ _objFinal.MAXBID
								+" Market Ask Price "+ _objFinal.MINASK
								+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator)
							);
						obj_2.Price =IPAddress.NetworkToHostOrder( _objFinal.MINASK);
						sendbuffer (Logic.Instance.GetPF (tradeconferm_manual (obj_2)));
						return;
					}
					else if (IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator) == 2 && IPAddress.HostToNetworkOrder (obj_1.Price) == 0)
					{
							Console.WriteLine (" 20000 Client Price  0:"+IPAddress.HostToNetworkOrder (obj_1.Price)
								+" Market Bid Price "+ _objFinal.MAXBID
								+" Market Ask Price "+ _objFinal.MINASK
								+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator)
								+"Tokenno"+IPAddress.HostToNetworkOrder (obj_1.TokenNo)
							);
						obj_2.Price =IPAddress.NetworkToHostOrder( _objFinal.MAXBID);
						sendbuffer (Logic.Instance.GetPF (tradeconferm_manual (obj_2)));
						return;
					}
					if (IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator) == 1) {
						if (IPAddress.HostToNetworkOrder (obj_1.Price) >= _objFinal.MINASK && _objFinal.MINASK>0) {
								Console.WriteLine (" 20000 Client Price without && if:"+IPAddress.HostToNetworkOrder (obj_1.Price)
									+" Market Bid Price "+ _objFinal.MAXBID
									+" Market Ask Price "+ _objFinal.MINASK
									+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator)
									+"Tokenno"+IPAddress.HostToNetworkOrder (obj_1.TokenNo)
								);
								obj_2.Price =IPAddress.NetworkToHostOrder( _objFinal.MINASK);
							sendbuffer (Logic.Instance.GetPF (tradeconferm_manual (obj_2)));
							}
		
					}

					if (IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator) == 2) {

							if (IPAddress.HostToNetworkOrder (obj_1.Price) <= _objFinal.MAXBID) {

								Console.WriteLine (" 20000 Client Price without && if:"+IPAddress.HostToNetworkOrder (obj_1.Price)
									+" Market Bid Price "+ _objFinal.MAXBID
									+" Market Ask Price "+ _objFinal.MINASK
									+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1.Buy_SellIndicator)
									+"Tokenno"+IPAddress.HostToNetworkOrder (obj_1.TokenNo)
								);
								obj_2.Price =IPAddress.NetworkToHostOrder( _objFinal.MAXBID);
								sendbuffer (Logic.Instance.GetPF (tradeconferm_manual (obj_2)));

						}
					}



				
                        break;
				case 20040:
						var obj_1ms = (MS_OM_REQUEST_TR)DataPacket.RawDeserialize (buffer, typeof(MS_OM_REQUEST_TR));
					if (UDP_RecieverData.Instance.TokenData.ContainsKey (IPAddress.HostToNetworkOrder (obj_1ms.TokenNo))) {
						var _MobjFinal = UDP_RecieverData.Instance.TokenData [IPAddress.HostToNetworkOrder (obj_1ms.TokenNo)];
					
						sendbuffer (Logic.Instance.GetPF (modifyfunction (obj_1ms)));
						if (IPAddress.HostToNetworkOrder (obj_1ms.Buy_SellIndicator) == 1) {

								if (IPAddress.HostToNetworkOrder (obj_1ms.Price) >= _MobjFinal.MINASK && _MobjFinal.MINASK > 0) {
									Console.WriteLine ("Client Price 20040 :" + IPAddress.HostToNetworkOrder (obj_1ms.Price) 
										+ " Market Ask Price " + _MobjFinal.MINASK
										+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1ms.Buy_SellIndicator)
										+"TokenNO "+IPAddress.HostToNetworkOrder (obj_1ms.TokenNo)
									);
									obj_1ms.Price =IPAddress.NetworkToHostOrder( _MobjFinal.MINASK);
								sendbuffer (Logic.Instance.GetPF (tradeconferm_Mod (obj_1ms)));
							} 
						} else {

								if (IPAddress.HostToNetworkOrder (obj_1ms.Price) <= _MobjFinal.MAXBID) {

									Console.WriteLine ("Client Price 20040 :" + IPAddress.HostToNetworkOrder (obj_1ms.Price) 
										+ " Market Ask Price " + _MobjFinal.MAXBID
										+"Buy_SellIndicator "+IPAddress.HostToNetworkOrder (obj_1ms.Buy_SellIndicator)
										+"TokenNO "+IPAddress.HostToNetworkOrder (obj_1ms.TokenNo)
									);
									obj_1ms.Price =IPAddress.NetworkToHostOrder( _MobjFinal.MAXBID);
								sendbuffer (Logic.Instance.GetPF (tradeconferm_Mod (obj_1ms)));
							} 
						}

						//Console.WriteLine (" 20074 "+DoubleEndianChange(obj_1ms.OrderNumber));

					}

                        break;
                    case 20070:
                        var obj_1cal = (MS_OM_REQUEST_TR)DataPacket.RawDeserialize(buffer, typeof(MS_OM_REQUEST_TR));
					sendbuffer(Logic.Instance.GetPF(cancelfunction(obj_1cal)));
						Console.WriteLine (" 20075 "+DoubleEndianChange(obj_1cal.OrderNumber)+" Tokenno"+IPAddress.HostToNetworkOrder (obj_1cal.TokenNo));
					break;

				case 2100:
					MS_SPD_OE_REQUEST msoespd = (MS_SPD_OE_REQUEST)DataPacket.RawDeserialize (buffer, typeof(MS_SPD_OE_REQUEST));
					msoespd.OrderNumber1 = DoubleEndianChange (Convert.ToInt64 (DateTime.Now.ToString ("HHmmssfff")) + count);
                        //    msoespd.OrderNumber1 = DoubleEndianChange(1110111258 + count);
                       /* if (count % 2 == 0)
                        {
                            msoespd.header_obj.TransactionCode = IPAddress.NetworkToHostOrder((short)2127);
                            sendbuffer(Logic.Instance.GetPF(DataPacket.RawSerialize(msoespd)));
                            return;
                        }*/
					++count;
					Console.WriteLine ("BuySell1 "+IPAddress.HostToNetworkOrder(msoespd.BuySell1));
					Console.WriteLine ("leg2 BuySell2 "+IPAddress.HostToNetworkOrder(msoespd.leg2.BuySell2));
                        msoespd.header_obj.TransactionCode = IPAddress.NetworkToHostOrder((short)2124);
                        sendbuffer(Logic.Instance.GetPF(DataPacket.RawSerialize(msoespd)));

                        tradeconfermiocistleg(msoespd);//
					sendbuffer(Logic.Instance.GetPF(tradeconfermioc2ndleg(msoespd)));

                        //sendbuffer(Logic.Instance.GetPF(tradeconfermioc2ndleg(msoespd)));
					//sendbuffer (Logic.Instance.GetPF (tradeconferm_manual (msoespd)));
                        break;
                }
            }
            else
            {
                var _checkval = (Message_Header)DataPacket.RawDeserialize(buffer, typeof(Message_Header));
                int trcode = IPAddress.NetworkToHostOrder(_checkval.TransactionCode);
            }
        }
		}
        private FinalPrice GetRates(SourceDestination sourceDestination)
        {
            FinalPrice  finalPrice = new FinalPrice();
            List <rate> finalRate  = new List <rate>();

            var url = "https://ct.soa-gw.canadapost.ca/rs/ship/price"; // REST URL

            var    method           = "POST";                          // HTTP Method
            String responseAsString = "";

            // Create mailingScenario object to contain xml request
            mailingscenario mailingScenario = new mailingscenario();

            mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics();
            mailingScenario.destination           = new mailingscenarioDestination();
            mailingscenarioDestinationDomestic destDom = new mailingscenarioDestinationDomestic();

            mailingScenario.destination.Item = destDom;


            String modifiedOrigin      = Regex.Replace(sourceDestination.originpostalcode, @"\s", "");
            String modifiedDestination = Regex.Replace(sourceDestination.destinationpostalcode, @"\s", "");

            // Populate mailingScenario object
            mailingScenario.customernumber = "2004381";
            mailingScenario.parcelcharacteristics.weight = sourceDestination.parcelweight;
            mailingScenario.originpostalcode             = modifiedOrigin.Trim();
            destDom.postalcode = modifiedDestination.Trim();

            try
            {
                // Serialize mailingScenario object to String
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.1\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                // Create REST Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                // Set Basic Authentication Header using username and password variables
                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("6e93d53968881714" + ":" + "0bfa9fcb9853d1f51ee57a"));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                // Write Post Data to Request
                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                // Execute REST Request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode.ToString() == "OK")
                {
                    // Deserialize response to pricequotes object
                    XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                    TextReader    reader      = new StreamReader(response.GetResponseStream());
                    pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);

                    // Retrieve values from pricequotes object
                    foreach (var priceQuote in priceQuotes.pricequote)
                    {
                        finalRate.Add(new rate {
                            RegularPrice = priceQuote.pricedetails.due, ServiceType = priceQuote.servicename, TransitDay = Convert.ToInt16(priceQuote.servicestandard.expectedtransittime)
                        });
                    }
                    finalPrice.RatesList             = finalRate;
                    finalPrice.originpostalcode      = sourceDestination.originpostalcode;
                    finalPrice.destinationpostalcode = sourceDestination.destinationpostalcode;
                    finalPrice.parcelweight          = sourceDestination.parcelweight;
                }
                else
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(messages));
                    TextReader    reader     = new StreamReader(response.GetResponseStream());
                    messages      myMessages = (messages)serializer.Deserialize(reader);


                    if (myMessages.message != null)
                    {
                        foreach (var item in myMessages.message)
                        {
                            responseAsString    += "Error Code: " + item.code + "\r\n";
                            responseAsString    += "Error Msg: " + item.description + "\r\n";
                            ViewBag.ErrorMessage = responseAsString;
                        }
                    }
                }
            }
            catch (WebException webEx)
            {
                HttpWebResponse response = (HttpWebResponse)webEx.Response;

                if (response != null)
                {
                    //responseAsString += "HTTP  Response Status: " + webEx.Message + "\r\n";

                    // Retrieve errors from messages object
                    try
                    {
                        // Deserialize xml response to messages object
                        XmlSerializer serializer = new XmlSerializer(typeof(messages));
                        TextReader    reader     = new StreamReader(response.GetResponseStream());
                        messages      myMessages = (messages)serializer.Deserialize(reader);


                        if (myMessages.message != null)
                        {
                            foreach (var item in myMessages.message)
                            {
                                responseAsString    += "Error Code: " + item.code + "\r\n";
                                responseAsString    += "Error Msg: " + item.description + "\r\n";
                                ViewBag.ErrorMessage = responseAsString;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Misc Exception
                        responseAsString    += "ERROR: " + ex.Message;
                        ViewBag.ErrorMessage = responseAsString;
                    }
                }
                else
                {
                    // Invalid Request
                    responseAsString    += "ERROR: " + webEx.Message;
                    ViewBag.ErrorMessage = responseAsString;
                }
            }
            catch (Exception ex)
            {
                // Misc Exception
                responseAsString    += "ERROR: " + ex.Message;
                ViewBag.ErrorMessage = responseAsString;
            }

            return(finalPrice);
        }
Esempio n. 12
0
        internal void UDPReciever(String LanIP = "127.0.0.1", string McastIp = "226.1.1.1" /* "239.70.70.21"*/, int port = 5050)   //10821)   //  internal void UDPReciever(String LanIP = "127.0.0.1", string McastIp = "233.1.2.5", int port = 34330)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            s.ExclusiveAddressUse = false;
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, Convert.ToInt32(port));

            s.Bind(ipep);
            IPAddress ip = IPAddress.Parse(McastIp);

            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Parse("127.0.0.1")));

            byte[] r_req = new byte[BufferSize];
            try
            {
                //Task.Run(() =>
                Task.Factory.StartNew(() =>
                {
                    while (!cts.IsCancellationRequested)
                    {
                        int size = s.Receive(r_req);
                        if (size > 0)
                        {
                            FinalPrice _obj = (FinalPrice)DataPacket.RawDeserialize(r_req, typeof(FinalPrice));
                            //Console.WriteLine("Token {0} Bid {1} Ask {2} LTP {3}",_obj.Token,_obj.MAXBID,_obj.MINASK,_obj.LTP);

                            if (_iSubscribe.Contains(_obj.Token))
                            {
                                OnDataArrived.Raise(OnDataArrived, OnDataArrived.CreateReadOnlyArgs(_obj));
                            }
                        }
                        cts.Token.ThrowIfCancellationRequested();
                    }
                }, cts.Token);
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Cancellation invoked");
            }
            catch (AggregateException e)
            {
                if (e.InnerException is OperationCanceledException)
                {
                    if (s != null)
                    {
                        if (s.Connected)
                        {
                            s.Shutdown(SocketShutdown.Both);
                            s.Close();
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Some unexpected exception ");
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception Raised " + Ex.Message);
            }
        }