private ActionResult ProcessUpdateCartNum() { #region 购物车 VWShoppingCartInfo shoppingCart = SessionUtil.GetCartSession(); #endregion string callback = QueryString.SafeQ("callback");//jsonp回调函数 int productdetailid = QueryString.IntSafeQ("prodetailid"); int num = QueryString.IntSafeQ("Num"); if (productdetailid == 0) { return(Content(callback + "({\"Status\":\"请选择需要删除的商品\"});")); } else { ShoppingCartProcessor.UpdateCarItemQty(shoppingCart, productdetailid, num); return(Content(callback + "({\"Status\":\"OK\"});")); } }
private ActionResult ProcessDelFromCartXuQiu() { #region 购物车 VWShoppingCartInfo shoppingCart = SessionUtil.GetXuQiuSession(); #endregion string callback = QueryString.SafeQ("callback");//jsonp回调函数 int prodetailid = QueryString.IntSafeQ("prodetailid"); int num = QueryString.IntSafeQ("Num"); if (prodetailid == 0) { return(Content(callback + "({\"Status\":\"请选择需要删除的商品\"});")); } else { ShoppingXuQiuProcessor.RemoveXuQiuItem(shoppingCart, prodetailid); return(Content(callback + "({\"Status\":\"OK\"});")); } }
//public static void PushToActiveMQ(T opldObject, int queueNumber) //{ // Uri connecturi = new Uri("activemq:tcp://localhost:61616"); // // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. // IConnectionFactory factory = new NMSConnectionFactory(connecturi); // using (IConnection connection = factory.CreateConnection()) // using (ISession session = connection.CreateSession()) // { // IDestination destination = SessionUtil.GetDestination(session, GETQueueName(queueNumber)); // // Create the producer // using (IMessageProducer producer = session.CreateProducer(destination)) // { // // Start the connection so that messages will be processed. // connection.Start(); // producer.DeliveryMode = MsgDeliveryMode.Persistent; // var messageToQueue = JsonConvert.SerializeObject(opldObject); // //var ss = "Test Message " + DateTime.Now; // ITextMessage request = session.CreateTextMessage(messageToQueue); // request.NMSCorrelationID = "abc"; // //request.Properties["NMSXGroupID"] = "cheese"; // //request.Properties["myHeader"] = "Cheddar"; // producer.Send(request); // } // } //} public static OPLD PullFromActiveMQ() { try { Uri connecturi = new Uri("activemq:tcp://54.173.238.145:61616"); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, "queue://OPLDProcess"); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); producer.DeliveryMode = MsgDeliveryMode.Persistent; // Consume a message ITextMessage message = consumer.Receive() as ITextMessage; if (message == null) { return(default(OPLD)); } else { OPLD opld = Newtonsoft.Json.JsonConvert.DeserializeObject <OPLD>(message.Text); return(opld); } } } } catch { return(default(OPLD)); } }
protected void btnSave_Click(object sender, EventArgs e) { Hashtable tbXe = new Hashtable(); tbXe.Add("Bienso", txtBienSo.Text); tbXe.Add("TenXe", txtTenXe.Text); tbXe.Add("Nhaxe", ddlNhaxe.SelectedValue); tbXe.Add("Hangxe", ddlHangXe.SelectedValue); tbXe.Add("Gioithieungan", txtGioiThieu.Text); tbXe.Add("Gioithieuchitiet", txtChiTiet.Text); tbXe.Add("Daxoa", ckDel.Checked == true ? "0" : "1"); tbXe.Add("Tongsoghe", txtSoGhe.Text); tbXe.Add("Avartar", txtAvartar.Text); if (string.IsNullOrEmpty(maxe)) { tbXe.Add("NgayTao", DateTime.Now.ToString("MM/dd/yyyy")); tbXe.Add("Nguoitao", Session["UserName"].ToString()); bool _insertXe = UpdateData.Insert("Xe", tbXe); if (_insertXe) { SessionUtil.SetKey("Message", string.Format(ErrorMessage.Success, "Thêm xe mới")); ltrScript.Text = ("<script>parent.window.location.reload();</script>"); } else { Value.ShowMessage(ltrError, string.Format(ErrorMessage.Fail, "Thêm mới xe"), AlertType.ERROR); } } else { bool _updateXe = UpdateData.Update("Xe", tbXe, "Maxe=" + maxe); if (_updateXe) { ltrScript.Text = ("<script>parent.HideModal('#add-modal'); parent.window.location.reload();</script>"); } else { Value.ShowMessage(ltrError, string.Format(ErrorMessage.Fail, "Sửa xe"), AlertType.ERROR); } } }
public void SendReceiveNMSProperties( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using (IConnection connection = CreateConnection(GetTestClientId())) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { producer.Priority = priority; producer.DeliveryMode = deliveryMode; ITextMessage request = session.CreateTextMessage(expectedText); // Set the headers request.NMSCorrelationID = correlationID; request.NMSType = type; request.Properties["NMSXGroupID"] = groupID; request.Properties["NMSXGroupSeq"] = groupSeq; producer.Send(request); ITextMessage message = consumer.Receive(receiveTimeout) as ITextMessage; Assert.IsNotNull(message, "Did not receive an ITextMessage!"); Assert.AreEqual(expectedText, message.Text, "Message text does not match."); // compare standard NMS headers Assert.AreEqual(correlationID, message.NMSCorrelationID, "NMSCorrelationID does not match"); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); Assert.AreEqual(priority, message.NMSPriority, "NMSPriority does not match"); Assert.AreEqual(type, message.NMSType, "NMSType does not match"); Assert.AreEqual(groupID, message.Properties["NMSXGroupID"], "NMSXGroupID does not match"); Assert.AreEqual(groupSeq, message.Properties["NMSXGroupSeq"], "NMSXGroupSeq does not match"); } } } }
private async Task DoConfigurePack(bool forceRebuild) { var updating = this.currentPackState == PackMode.NeedsUpdate; var actionName = updating ? "Updating" : forceRebuild ? "Rebuilding" : "Installing"; var dialog = new ProgressDialog($"{actionName} Mod Pack") { ConfirmCancel = true }; var cancelSource = new CancellationTokenSource(); var successful = false; // Don't need to do this, necessarily, but to be polite to Mojang, we should check // for a valid session *before* downloading all of the Minecraft assets. var session = await SessionUtil.GetSessionAsync(this); if (session == null) { return; } dialog.Cancel += (_, _) => { cancelSource.Cancel(); dialog.Reporter.ReportProgress(-1, "Cancelling...please wait"); }; dialog.Show(this); try { var useCanaryVersion = this.chkUseCanaryVersion.Checked; await this.packBuilder.SetupPackAsync(this.packMetadata, forceRebuild || !updating, useCanaryVersion, cancelSource.Token, dialog.Reporter); successful = true; } catch (Exception ex) when(ex is TaskCanceledException or OperationCanceledException or WebException { Status: WebExceptionStatus.RequestCanceled })
public ActionResult Index() { ViewData["Message"] = "Welcome to the C# Assignment Framework"; //Get the enrollments for the active user Team team = SessionUtil.GetTeamFromFormsAuthentication(); if (team != null) { List <AssignmentEnrollment> enrollmentList = ClientFacade.Instance.GetAssignmentEnrollmentsForTeam(team.Id); team = ClientFacade.Instance.GetTeamById(team.Id); // Set up the model HomeModel hm = new HomeModel(); hm.TeamName = team.Name; hm.MembersModel = new MembersModel() { Members = team.Members }; hm.EnrollmentList = new List <EnrollmentModel>(); foreach (AssignmentEnrollment ae in enrollmentList) { hm.EnrollmentList.Add(new EnrollmentModel() { AssignmentEnrollmentId = ae.Id, AssignmentName = ae.TournamentAssignment.Assignment.Name, TournamentName = ae.TournamentAssignment.Tournament.Name }); } return(View(hm)); } else { return(View()); } }
private async void SendMessagesAsync() { _producerSession = _connectionQ2.CreateSession(AcknowledgementMode.AutoAcknowledge); var producerDestination = SessionUtil.GetDestination(_producerSession, $"queue://{_queue2Config.OutgoingQueue}"); var producer = _producerSession.CreateProducer(producerDestination); var credentials = _queue2Config.Credentials; await Task.Delay(10000); var msg1 = _producerSession.CreateMessage(); msg1.Properties.SetString("messageId", "123"); msg1.Properties.SetString("user", credentials.Login); msg1.Properties.SetString("password", credentials.Password); msg1.Properties.SetString("messageInfo", "msg1"); producer.Send(msg1); await Task.Delay(2000); var msg2 = _producerSession.CreateMessage(); msg2.Properties.SetString("messageId", "456"); msg2.Properties.SetString("user", credentials.Login); msg2.Properties.SetString("password", credentials.Password); msg2.Properties.SetString("messageInfo", "msg2"); producer.Send(msg2); await Task.Delay(2000); var msg3 = _producerSession.CreateMessage(); msg3.Properties.SetString("messageId", "789"); msg3.Properties.SetString("user", credentials.Login); msg3.Properties.SetString("password", credentials.Password); msg3.Properties.SetString("messageInfo", "msg3"); producer.Send(msg3); await Task.Delay(2000); }
/// <summary> /// Create a destination. This will delete an existing destination and re-create it. /// </summary> /// <param name="session"></param> /// <param name="destinationName"></param> /// <returns></returns> public virtual IDestination CreateDestination(ISession session, string destinationName) { try { SessionUtil.DeleteDestination(session, destinationName); } catch (Exception) { // Can't delete it, so lets try and purge it. IDestination destination = SessionUtil.GetDestination(session, destinationName); using (IMessageConsumer consumer = session.CreateConsumer(destination)) { while (consumer.Receive(TimeSpan.FromMilliseconds(750)) != null) { } } } return(SessionUtil.GetDestination(session, destinationName)); }
public void ProduceMessage(string msgBody, IDictionary <string, string> properties = null) { using (ISession session = _queueConnection.CreateSession(AcknowledgementMode.ClientAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, "queue://Email"); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = MsgDeliveryMode.Persistent; ITextMessage request = session.CreateTextMessage(msgBody); foreach (var kv in properties) { request.Properties[kv.Key] = kv.Value; } producer.Send(request); } } }
static void Main(string[] args) { String QueuesNameESF = "queue://test.log"; Uri _uri = new Uri(String.Concat("activemq:tcp://127.0.0.1:61616")); IConnectionFactory factory = new ConnectionFactory(_uri); using (IConnection conn = factory.CreateConnection("admin", "manager")) { using (ISession session = conn.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, QueuesNameESF); using (IMessageProducer producer = session.CreateProducer(destination)) { conn.Start(); //可以写入字符串,也可以是一个xml字符串等 ITextMessage request = session.CreateTextMessage("messsage"); producer.Send(request); } } } }
/// <summary> /// Sends a message on the current output channel within a specified interval of time. /// </summary> /// <param name="message">The <see cref="T:System.ServiceModel.Channels.Message" /> being sent on the output channel.</param> /// <param name="timeout">The <see cref="T:System.TimeSpan" /> that specifies how long the send operation has to complete before timing out.</param> public void Send(Message message, TimeSpan timeout) { ThrowIfDisposedOrNotOpen(); RemoteAddress.ApplyTo(message); using (NMS.ISession session = _connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, Destination, DestinationType); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = MsgDeliveryMode.Persistent; ITextMessage request = session.CreateTextMessage(TranslateMessage(message)); producer.Send(request); producer.Close(); Tracer.Info("Sending message:"); Tracer.Info(request.Text); } } }
public void ConsumeInTwoThreads() { ParameterizedThreadStart threadStart = delegate(object o) { IMessageConsumer consumer = (IMessageConsumer)o; IMessage message = consumer.Receive(TimeSpan.FromSeconds(2)); Assert.IsNotNull(message); }; using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) { IQueue queue = SessionUtil.GetDestination(session, DESTINATION_NAME) as IQueue; // enqueue 2 messages using (IMessageConsumer consumer = session.CreateConsumer(queue)) using (IMessageProducer producer = session.CreateProducer(queue)) { producer.DeliveryMode = MsgDeliveryMode.Persistent; producer.Send(producer.CreateMessage()); producer.Send(producer.CreateMessage()); session.Commit(); // receive first using a dedicated thread. This works Thread thread = new Thread(threadStart); thread.Start(consumer); thread.Join(); session.Commit(); // receive second using main thread. This FAILS IMessage message = consumer.Receive(TimeSpan.FromSeconds(2)); // throws System.Threading.AbandonedMutexException Assert.IsNotNull(message); session.Commit(); } } } }
/// <summary> /// Obtiene el ultimo mensaje encolado del MOM. /// </summary> /// <returns>Mensaje en cadena.</returns> public async Task RecibirMensajeActiveMQAsync(List <string> queueNameOrigenes, EnumeradosTraductor.DireccionMensaje direccion, EnumeradosTraductor.TipoConversionMensaje tipo) { try { string _queueName = string.Empty; CrearConexion(ServidorBrokerUri, AcknowledgementMode.ClientAcknowledge); _queueName = queueNameOrigenes[0]; IDestination dest = SessionUtil.GetDestination(Session, QueueName); using (IMessageConsumer consumer = Session.CreateConsumer(dest)) { IMessage message; message = consumer.Receive(TimeSpan.FromSeconds(TiempoEsperaRecepcionMensaje)); if (message != null) { CondicionesMensaje condicionesMensaje = new CondicionesMensaje( message, direccion, tipo, _queueName); OnMensajeRecibido(condicionesMensaje); } } } catch (Exception ex) { Log.Error(ex, Constantes.MsgLog.ERRORMETODO, nameof(RecibirMensajeActiveMQAsync)); throw ex; } finally { if (Connection != null) { Connection.Close(); } } }
void ApolloWriter() { #if !UNITY_EDITOR && UNITY_METRO throw new System.NotImplementedException(); #else try { IDestination destination_Write = SessionUtil.GetDestination(session, topicWrite); IMessageProducer defaultProducer = session.CreateProducer(destination_Write); defaultProducer.DeliveryMode = MsgDeliveryMode.NonPersistent; defaultProducer.RequestTimeout = receiveTimeout; while (networkOpen) { MSG msg = new MSG(""); lock (_sendQueueLock) { if (_sendQueue.Count > 0) { msg = _sendQueue.Dequeue(); } } if (msg.data.Length > 0) { if (msg.src.Length == 0) { defaultProducer.Send(session.CreateTextMessage(msg.data)); } else { IMessageProducer producer = session.CreateProducer(SessionUtil.GetDestination(session, msg.src)); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; producer.RequestTimeout = receiveTimeout; producer.Send(session.CreateTextMessage(msg.data)); } } } } catch (System.Exception e) { Debug.Log("ApolloWriter Exception " + e); } #endif }
public void TestReceiveTwoThenRollback() { using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { producer.Persistent = false; producer.RequestTimeout = receiveTimeout; // Send both messages ITextMessage firstMsgSend = session.CreateTextMessage("First Message"); producer.Send(firstMsgSend); ITextMessage secondMsgSend = session.CreateTextMessage("Second Message"); producer.Send(secondMsgSend); session.Commit(); // Receive the messages IMessage message = consumer.Receive(receiveTimeout); AssertTextMessageEqual(firstMsgSend, message, "First message does not match."); message = consumer.Receive(receiveTimeout); AssertTextMessageEqual(secondMsgSend, message, "Second message does not match."); // Rollback so we can get that last two messages again. session.Rollback(); IMessage rollbackMsg = consumer.Receive(receiveTimeout); AssertTextMessageEqual(firstMsgSend, rollbackMsg, "First rollback message does not match."); rollbackMsg = consumer.Receive(receiveTimeout); AssertTextMessageEqual(secondMsgSend, rollbackMsg, "Second rollback message does not match."); Assert.IsNull(consumer.ReceiveNoWait()); session.Commit(); } } } }
private void button1_Click(object sender, EventArgs e) { IObjectMessage objMessage; RequesterObject Request = new RequesterObject(); Request.Requestproerty = textBox1.Text.ToString(); IConnectionFactory factory = new NMSConnectionFactory("tcp://localhost/"); IConnection connection = factory.CreateConnection(); connection = factory.CreateConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination QueueDestination = SessionUtil.GetDestination(session, "Queue"); IMessageProducer MessageProducer = session.CreateProducer(QueueDestination); objMessage = session.CreateObjectMessage(Request); MessageProducer.Send(objMessage); session.Close(); connection.Stop(); }
/// <summary> /// メンバをネットワークバイトオーダーからホストバイトオーダーに変換する /// </summary> public virtual void ntoh() { FieldInfo[] fis = this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo fi in fis) { if (fi.GetValue(this) is Int16) { fi.SetValue(this, SessionUtil.ntoh((Int16)fi.GetValue(this))); } else if (fi.GetValue(this) is UInt16) { fi.SetValue(this, SessionUtil.ntoh((UInt16)fi.GetValue(this))); } else if (fi.GetValue(this) is Int32) { fi.SetValue(this, SessionUtil.ntoh((Int32)fi.GetValue(this))); } else if (fi.GetValue(this) is UInt32) { fi.SetValue(this, SessionUtil.ntoh((UInt32)fi.GetValue(this))); } else if (fi.GetValue(this) is Int64) { fi.SetValue(this, SessionUtil.ntoh((Int64)fi.GetValue(this))); } else if (fi.GetValue(this) is UInt64) { fi.SetValue(this, SessionUtil.ntoh((UInt64)fi.GetValue(this))); } else if (fi.GetValue(this) is ServerState) { fi.SetValue(this, SessionUtil.ntoh((uint)fi.GetValue(this))); } else { //throw new NotImplementedException("エンディアン変換に対応していない型です。"); } } }
// Use this for initialization void Start() { //Allow application to run in the background Application.runInBackground = true; connectionIndicator.color = Color.yellow; this.player = GameObject.FindObjectOfType <Player>(); this.connectionConfirmed = false; if (this.player == null) { //return to menu } else { this.gameID = this.player.GameCode; this.userID = mTurnJSON.GetColourString(this.player.PlayerColour); } this.connectUri = new Uri("activemq:" + connectionUri); this.factory = new NMSConnectionFactory(connectUri); this.connection = factory.CreateConnection(); this.connection.ClientId = this.userID; this.ReloadData(); session = connection.CreateSession(); destination = SessionUtil.GetDestination(session, queue + queueVar); consumer = session.CreateConsumer(destination); // Create a consumer and producer consumer.Listener += new MessageListener(OnMessage); connection.RedeliveryPolicy = new Apache.NMS.Policies.RedeliveryPolicy() { MaximumRedeliveries = 0 }; //TODO: remove? connection.Start(); selfReference = this; }
public IActionResult CheckAMQ(AmqModel model) { var url = model.Url; if (url != null && url.Length > 0) { try { OperatorRequestObject operatorRequestObject = new OperatorRequestObject { ShortCode = "ABC" }; Uri uri = new Uri("activemq:" + url); IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(uri); IConnection connection = factory.CreateConnection(); // ("admin", "admin"); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination queueDestination = SessionUtil.GetDestination(session, "ExampleQueue"); IMessageProducer messageProducer = session.CreateProducer(queueDestination); var objMessage = session.CreateObjectMessage(operatorRequestObject); messageProducer.Send(objMessage); session.Close(); connection.Stop(); ViewData["Message"] = "All Fine even after romving Creds"; } catch (Exception ex) { ViewData["Message"] = ex.Message; } } else { ViewData["Message"] = "No URL"; } return(View("Index")); }
public void TestSendRollback() { using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { producer.Persistent = false; producer.RequestTimeout = receiveTimeout; ITextMessage firstMsgSend = session.CreateTextMessage("First Message"); producer.Send(firstMsgSend); session.Commit(); ITextMessage rollbackMsg = session.CreateTextMessage("I'm going to get rolled back."); producer.Send(rollbackMsg); session.Rollback(); ITextMessage secondMsgSend = session.CreateTextMessage("Second Message"); producer.Send(secondMsgSend); session.Commit(); // Receive the messages IMessage message = consumer.Receive(receiveTimeout); AssertTextMessageEqual(firstMsgSend, message, "First message does not match."); message = consumer.Receive(receiveTimeout); AssertTextMessageEqual(secondMsgSend, message, "Second message does not match."); // validates that the rollback was not consumed session.Commit(); } } } }
public void SendReceiveBytesMessageContent( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using (IConnection connection = CreateConnection(GetTestClientId())) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = deliveryMode; IBytesMessage request = session.CreateBytesMessage(); request.WriteBoolean(true); request.WriteByte((byte)1); request.WriteBytes(new byte[1]); request.WriteBytes(new byte[3], 0, 2); request.WriteChar('a'); request.WriteDouble(1.5); request.WriteSingle((float)1.5); request.WriteInt32(1); request.WriteInt64(1); request.WriteObject("stringobj"); request.WriteInt16((short)1); request.WriteString("utfstring"); producer.Send(request); IMessage message = consumer.Receive(receiveTimeout); AssertMessageIsReadOnly(message); AssertBytesMessageEqual(request, message); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); } } } }
public void SendReceiveForeignMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using (IConnection connection = CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; Message request = new Message(); request.Properties[propertyName] = propertyValue; producer.Send(request); IMessage message = consumer.Receive(receiveTimeout); Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch (NotSupportedException) { } } } } }
public void TestRequestResponseMessaging() { using (IConnection connection = CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); ITemporaryQueue replyTo = session.CreateTemporaryQueue(); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { IMessage request = session.CreateMessage(); request.NMSReplyTo = replyTo; producer.Send(request); request = consumer.Receive(TimeSpan.FromMilliseconds(3000)); Assert.IsNotNull(request); Assert.IsNotNull(request.NMSReplyTo); using (IMessageProducer responder = session.CreateProducer(request.NMSReplyTo)) { IMessage response = session.CreateTextMessage("RESPONSE"); responder.Send(response); } } using (IMessageConsumer consumer = session.CreateConsumer(replyTo)) { ITextMessage response = consumer.Receive(TimeSpan.FromMilliseconds(3000)) as ITextMessage; Assert.IsNotNull(response); Assert.AreEqual("RESPONSE", response.Text); } } } }
public ActionResult SelectAssignment(int assignmentId, int tournamentAssignmentId, string assignmentName) { //Team team = SessionUtil.GetTeamFromFormsAuthentication(); Tournament t = SessionUtil.GetTournamentFromSession(); if (t == null) { return(RedirectToAction("Index")); } // Check for existence of tournamentAssignment TournamentAssignment ta = ClientFacade.Instance.GetTournamentAssignmentById(tournamentAssignmentId, false); if (ta == null) { return(RedirectToAction("Assignments")); } //Check if the tournamentassignment is active if (!ta.IsActive) { return(RedirectToAction("Assignments")); } // Check if the tournamentassignment is part of the selected tournament if (ta.Tournament.Id != t.Id) { return(RedirectToAction("Index")); } // Set session context SessionUtil.SetSession(t, ta, new Assignment() { Id = ta.Assignment.Id, Name = ta.Assignment.Name }, null); return(RedirectToAction("Index", "CurrentAssignment")); }
public ActionResult UserCreateEdit(USER user, FormCollection frm, HttpPostedFileBase UserPhoto) { if (UserPhoto != null) { #region Attache Documents string fileName = string.Empty; List <String> arrfileName = new List <String>(); int loop = 0; // Verify that the user selected a file if (UserPhoto != null && UserPhoto.ContentLength > 0) { // extract only the fielname fileName = Guid.NewGuid() + "_" + SessionUtil.GetUserID() + "_" + Path.GetFileName(UserPhoto.FileName); fileName = System.DateTime.Now.Millisecond.ToString() + Path.GetFileName(UserPhoto.FileName); var path = Path.Combine(Server.MapPath("~/Files/UsersPhoto/"), fileName); UserPhoto.SaveAs(path); arrfileName.Add(fileName); } else { arrfileName.Add("NA.JPG"); } loop++; user.UserPhoto = arrfileName[0].ToString(); #endregion } string pass = frm["pass"] != null ? frm["pass"] : ""; result = companyUtil.PostUserEdit(user, pass); switch (result.MessageType) { case MessageType.Success: return(RedirectToAction("CompanyTabs", "Company", new { id = user.CompanyId, Result = result.Message, MessageType = result.MessageType })); default: return(RedirectToAction("CompanyTabs", "Company", new { id = user.CompanyId, Result = result.Message, MessageType = result.MessageType })); } }
/// <summary> /// 创建生产者 /// </summary> /// <returns></returns> private IMessageProducer CreateProducer() { IMessageProducer producer = null; try { // 连接工厂是用户创建连接的对象. if (_connectionFactory == null) { Uri connectUri = new Uri("activemq:failover:(" + _brokerUrl + ")"); _connectionFactory = new NMSConnectionFactory(connectUri); } // 通过连接工厂获取连接 this._connection = this._connectionFactory.CreateConnection(); if (_connection != null) { this._connection.ConnectionInterruptedListener += connection_ConnectionInterruptedListener; // 启动连接 this._connection.Start(); // 创建_session // this._session = this._connection.CreateSession(AcknowledgementMode.AutoAcknowledge); this._session = this._connection.CreateSession(); // 消息的目的地 this._destination = SessionUtil.GetDestination(_session, "topic://" + this._topic); // 创建消息生产者 producer = this._session.CreateProducer(this._destination); // 设置是否持久化 producer.DeliveryMode = (_isPersitent ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent); } } catch (Exception ex) { Close(); LogHelper.WriteErrorLog(string.Format("ActiveMQ创建生产者异常:{0}", ex.Message)); } return(producer); }
private void StartSession() { //authentication data to connect to NativeAPI Bridge RedApp (ActiveMQ Broker) String user = "******"; String password = "******"; String host = "localhost"; int port = int.Parse("61616"); String redAppID = "com.sabre.tn.redapp.example.nativeApi"; String userID = System.Environment.GetEnvironmentVariable("USERNAME"); String domainID = System.Environment.GetEnvironmentVariable("USERDOMAIN"); //Create connection Uri connectUri = new Uri("activemq:tcp://" + host + ":" + port); IConnectionFactory factory = new NMSConnectionFactory(connectUri); connection = factory.CreateConnection(user, password); connection.Start(); //Start a session session = connection.CreateSession(); //Get address for request / reponse queues destinationRQ = SessionUtil.GetDestination(session, redAppID + "_" + domainID + "\\" + userID + RQ_QUEUE_SUFFIX); destinationRS = SessionUtil.GetDestination(session, redAppID + "_" + domainID + "\\" + userID + RS_QUEUE_SUFFIX); // create request producer producer = session.CreateProducer(destinationRQ); producer.DeliveryMode = MsgDeliveryMode.Persistent; // create a consumee for responses queue, would receive and "parse" all messages from Bridge RedApp // note that it will work "assynchronously", that is, the broker can "push" messages to client, without need to "pool" consumer = session.CreateConsumer(destinationRS); consumer.Listener += new MessageListener(onMessageAuto); }
protected void RunTestDurableConsumerTransactional() { SendPersistentMessage(); using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) { ITopic topic = SessionUtil.GetTopic(session, TOPIC); using (IMessageConsumer consumer = session.CreateDurableConsumer(topic, CONSUMER_ID, DURABLE_SELECTOR, false)) { IMessage msg = consumer.Receive(receiveTimeout); Assert.IsNotNull(msg, "Did not receive first durable transactional message."); SendPersistentMessage(); msg = consumer.Receive(receiveTimeout); Assert.IsNotNull(msg, "Did not receive second durable transactional message."); session.Commit(); } } } }
private Boolean DoLogout(String name) { ITextMessage request = _session.CreateTextMessage("logout"); //request.NMSReplyTo = _readQueue; request.Properties["Name"] = name; Trace.TraceInformation("Sending logout for '{0}'", name); IDestination destination = SessionUtil.GetDestination(_session, "topic://fennecfox.listeners"); using (IMessageProducer loginTopic = _session.CreateProducer(destination)) { try { loginTopic.Send(request); } catch (RequestTimedOutException) { Trace.TraceInformation("*** Timeout sending login for '{0}'", name); return(false); } } return(true); }