Exemplo n.º 1
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public TagDefinitionKey(TagValue schema, TagValue series, TagValue extendedValue, TagValue value)
 {
     this.schema = schema;
     this.series = series;
     this.extendedValue = extendedValue;
     this.value = value;
 }
Exemplo n.º 2
0
 public static PSTagValue ToPSTagValue(this TagValue value)
 {
     return(new PSTagValue()
     {
         Count = value.Count.Value,
         Name = value.Value
     });
 }
Exemplo n.º 3
0
        //private Stopwatch mCosStopwatch;
        //private Stopwatch mSinStopwatch;
        //private Stopwatch mStepStopwatch;
        /// <summary>
        ///
        /// </summary>
        private void CosThreadPro()
        {
            ThreadHelper.AssignToCPU(CPUAssignHelper.Helper.CPUArray2);
            List <Tagbase> vv  = mTagIdCach.ContainsKey("Sim:cos") ? mTagIdCach["Sim:cos"] : null;
            List <int>     vvr = mManualRecordTagCach.ContainsKey("Sim:cos") ? mManualRecordTagCach["Sim:cos"] : null;

            //mCosStopwatch = new Stopwatch();
            while (!mIsClosed)
            {
                mCosEvent.WaitOne();
                mCosEvent.Reset();

                if (mCosNeedReload)
                {
                    vv             = mTagIdCach.ContainsKey("Sim:cos") ? mTagIdCach["Sim:cos"] : null;
                    vvr            = mManualRecordTagCach.ContainsKey("Sim:cos") ? mManualRecordTagCach["Sim:cos"] : null;
                    mCosNeedReload = false;
                }

                //mCosStopwatch.Restart();
                //long ll = 0;
                double fval = Math.Cos(mNumber / 180.0 * Math.PI);
                if (vv != null)
                {
                    mTagService.SetTagValue(vv, ref fval, 0);
                    //ll = mCosStopwatch.ElapsedMilliseconds;
                    mTagService.SubmiteNotifyChanged();
                }

                if (vvr != null && vvr.Count > 0)
                {
                    TagValue tv = new TagValue()
                    {
                        Quality = 0, Time = DateTime.UtcNow, Value = fval
                    };
                    foreach (var vvv in vvr)
                    {
                        mTagHisValueService.SetTagHisValue(vvv, tv);
                    }
                }

                //mCosStopwatch.Stop();

                //LoggerService.Service.Info("SimDriver", "设置变量耗时:" + ll + " 其他耗时:" + (mCosStopwatch.ElapsedMilliseconds - ll) + " count:" + vv.Count);

                var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
                lock (mLockObj)
                {
                    if (ts > mMaxProcessTimeSpan)
                    {
                        mMaxProcessTimeSpan = ts;
                        //mSelfProcessTimeSpan = mCosStopwatch.ElapsedMilliseconds;
                    }
                }

                Interlocked.Increment(ref mFinishCount);
            }
        }
Exemplo n.º 4
0
        public void CreateMetrics_CountAgg_ReturnsExpected()
        {
            var opts          = new CloudFoundryForwarderOptions();
            var stats         = new OpenCensusStats();
            var tagsComponent = new TagsComponent();
            var tagger        = tagsComponent.Tagger;
            var ep            = new MicrometerMetricWriter(opts, stats);

            IMeasureDouble testMeasure = MeasureDouble.Create("test.total", "test", MeasureUnit.Bytes);

            SetupTestView(stats, Count.Create(), testMeasure, "test.test1");

            ITagContext context1 = tagger
                                   .EmptyBuilder
                                   .Put(TagKey.Create("a"), TagValue.Create("v1"))
                                   .Put(TagKey.Create("b"), TagValue.Create("v1"))
                                   .Put(TagKey.Create("c"), TagValue.Create("v1"))
                                   .Build();

            long allKeyssum = 0;

            for (int i = 0; i < 10; i++)
            {
                allKeyssum = allKeyssum + i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context1);
            }

            var viewData = stats.ViewManager.GetView(ViewName.Create("test.test1"));

            Assert.NotNull(viewData);
            var aggMap = viewData.AggregationMap;

            Assert.Single(aggMap);

            var tagValues = aggMap.Keys.Single();
            var data      = aggMap.Values.Single();

            Assert.NotNull(tagValues);
            Assert.NotNull(data);

            var result = ep.CreateMetrics(viewData, data, tagValues, 1L);

            Assert.NotNull(result);
            Assert.Single(result);
            var metric = result[0];

            Assert.Equal("test.test1", metric.Name);
            Assert.Equal(1L, metric.Timestamp);
            Assert.Equal("gauge", metric.Type);
            Assert.Equal("bytes", metric.Unit);
            Assert.Equal(10, metric.Value);
            var tags = metric.Tags;

            Assert.Equal("count", tags["statistic"]);
            Assert.Equal("v1", tags["a"]);
            Assert.Equal("v1", tags["b"]);
            Assert.Equal("v1", tags["c"]);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Obtiene la información de un cliente dado
        /// </summary>
        /// <param name="sessionId">Session ID que será escrito en los logs</param>
        /// <param name="tipoIdentificacion">Tipo de identificación del cliente</param>
        /// <param name="numeroIdentificacion">Número de identificación del cliente</param>
        /// <param name="returnCode">Codigo de error en caso de que algo falle (-1 = OK, >-1 = Error)</param>
        /// <param name="connection">Objeto de conexión a base de datos</param>
        /// <returns>Un objeto <c>DwhModel.Cliente</c> que contiene la información del cliente</returns>
        private List <Cash472.DwhModel.Ciudad> GetListCities(string sessionId, out ErrorMessagesMnemonics returnCode, SqlConnection connection = null)
        {
            string methodName = string.Format("{0}", System.Reflection.MethodBase.GetCurrentMethod().Name);

            returnCode = ErrorMessagesMnemonics.None;
            List <Cash472.DwhModel.Ciudad> listCities = new List <DwhModel.Ciudad>();

            try
            {
                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Ejecutando query ..."));

                Dictionary <string, object> queryParams = null;
                if (connection == null)
                {
                    using (connection = Utils.Database.GetCash472DbConnection())
                    {
                        connection.Open();
                        listCities = Utils.Dwh <Cash472.DwhModel.Ciudad> .ExecuteReader(
                            connection,
                            Queries.Cash.ListCities,
                            queryParams,
                            null);
                    }
                }
                else
                {
                    listCities = Utils.Dwh <Cash472.DwhModel.Ciudad> .ExecuteReader(
                        connection,
                        Queries.Cash.ListCities,
                        queryParams,
                        null);
                }

                if (listCities == null || listCities.Count == 0)
                {
                    returnCode = ErrorMessagesMnemonics.ErrorGetCities;
                    listCities = null;
                }

                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Query ejecutado"));
            }
            catch (Exception ex)
            {
                this.ProviderLogger.ExceptionLow(() => TagValue.New()
                                                 .MethodName(methodName)
                                                 .Message("[" + sessionId + "] " + "Error ejecutando query")
                                                 .Exception(ex));
                returnCode = ErrorMessagesMnemonics.InternalDatabaseError;
                listCities = null;
            }

            return(listCities);
        }
Exemplo n.º 6
0
        public void PostWorkspacesWorkspaceIdTagvaluesTest()
        {
            // TODO: add unit test for the method 'PostWorkspacesWorkspaceIdTagvalues'
            string   workspaceId = null; // TODO: replace null with proper value
            TagValue body        = null; // TODO: replace null with proper value
            var      response    = instance.PostWorkspacesWorkspaceIdTagvalues(workspaceId, body);

            Assert.IsInstanceOf <TagValue> (response, "response is TagValue");
        }
Exemplo n.º 7
0
 private void button2_Click(object sender, EventArgs e)
 {
     iIndex       = 0;
     m_dtLineData = TagValue.QueryDBData(dateTimePickerBegin2.Value, dateTimePickerEnd2.Value, "*", UnitNO);
     foreach (DataRowView row in m_viewTagValue)
     {
         row["TagValue"] = m_dtLineData.Rows[iIndex]["F" + row["id"].ToString()];
     }
 }
 // TODO(sebright): Consider exposing a TagValue validation method to avoid needing to catch
 // an IllegalArgumentException here.
 private static ITagValue CreateTagValue(ITagKey key, String value)
 {
     try {
         return(TagValue.Create(value));
     } catch (Exception e) {
         throw new TagContextDeserializationException(
                   "Invalid tag value for key " + key + ": " + value, e);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Paso 1 emisión de un nuevo giro => Constitución del giro
        /// </summary>
        /// <param name="request">Objeto que contiene la información del giro</param>
        /// <param name="sessionId">ID de sesión para poner en los mensajes de log</param>
        /// <param name="exc">Excepción generada al llamar el servicio</param>
        /// <returns>Respuesta de la constitución del giro</returns>
        private MultiPay472.RespuestaValidacionConstitucionGiro EmitirPaso1Cash472(EmitirRequest request, string sessionId, out Exception exc)
        {
            string methodName = string.Format("{0}", System.Reflection.MethodBase.GetCurrentMethod().Name);

            exc = null;

            MultiPay472.RespuestaValidacionConstitucionGiro resp = null;
            MultiPay472.Service1SoapClient client = this.GetSoapClient();
            string endpointName = "ValidacionConstitucionGiro";

            try
            {
                MultiPay472.ValidacionConstitucionGiro peticion = new MultiPay472.ValidacionConstitucionGiro();
                peticion.NitRed            = this.multipayNitRed;
                peticion.CodigoTerminal    = this.multipayTerminal;
                peticion.CodigoTransaccion = this.GenerarCodigoTransaccion(sessionId);

                peticion.CodigoPuntoVenta             = request.Pdv;
                peticion.ValorRecibido                = request.ValorRecibido;
                peticion.IncluyeFlete                 = request.IncluyeFlete;
                peticion.CodigoDaneCiudadPuntoVenta   = request.CiudadPdv;
                peticion.CodigoDaneCiudadPagoSugerido = request.CiudadDestino;

                peticion.Originador = new MultiPay472.Originador();
                this.EstablecerValoresCliente472(request.Emisor, peticion.Originador, null);

                peticion.Destinatario = new MultiPay472.Destinatario();
                this.EstablecerValoresCliente472(request.Receptor, null, peticion.Destinatario);

                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Llamando servicio \"" + endpointName + "\" ..."));

                resp = client.ValidacionConstitucionGiro(peticion, this.multipayUsuario);

                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Respuesta servicio \"" + endpointName + "\"")
                                            .Tag("Respuesta").Value(resp != null ? resp.CodigoRespuesta : "NULL"));

                if (resp == null || resp.CodigoRespuesta != CashProvider.CodigoRespuestaExitoso)
                {
                    this.errorMessage = resp == null ? ErrorMessagesMnemonics.WebServiceDoesNotRespond : ErrorMessagesMnemonics.Cash472WsError;
                }
            }
            catch (Exception ex)
            {
                this.ProviderLogger.ExceptionLow(() => TagValue.New()
                                                 .MethodName(methodName)
                                                 .Message("[" + sessionId + "] " + "Error llamando servicio \"" + endpointName + "\"")
                                                 .Exception(ex));
                this.errorMessage = ErrorMessagesMnemonics.WebServiceException;
                exc = ex;
            }

            return(resp);
        }
Exemplo n.º 10
0
        public Tag GetTagFromCSV(string fileName, TagCSV tagCSV)
        {
            Tag tag = new Tag()
            {
                TagName = tagCSV.TagName, TagDescription = tagCSV.TagNameRus
            };

            StreamReader fileStream = OpenFile(fileName);

            string timeStampStr;
            string valueStr;

            string fistLine;

            if (fileStream != null)
            {
                fistLine = fileStream.ReadLine();
                fistLine = Regex.Replace(fistLine, "[@,%\\.\"'\\\\]", string.Empty);
                fistLine = fistLine.Replace("-", "_");
                fistLine = fistLine.Replace("/", "_");

                string[] headerLine = fistLine.Split(';');
                //string[] headerLine = fileStream.ReadLine().Split(';');

                //TODO: Доработать проверку что в этом  есть этот тег
                if (headerLine[tagCSV.TimeStampColumn].Contains(tagCSV.TagNameRus) && headerLine[tagCSV.ValueColumn].Contains(tagCSV.TagNameRus))
                {
                    NumberFormatInfo nfi = new NumberFormatInfo()
                    {
                        NumberDecimalSeparator = "."
                    };

                    while (fileStream.Peek() > 0)
                    {
                        string[] dataLine = fileStream.ReadLine().Split(';');

                        if (tagCSV.TimeStampColumn < dataLine.Length - 1 && tagCSV.ValueColumn < dataLine.Length - 1)
                        {
                            timeStampStr = dataLine[tagCSV.TimeStampColumn];
                            valueStr     = dataLine[tagCSV.ValueColumn];

                            if (!string.IsNullOrEmpty(timeStampStr) && !string.IsNullOrEmpty(valueStr))
                            {
                                TagValue tagValue = new TagValue();
                                //tagValue.ValueString = valueStr.Trim();
                                tagValue.ValueFloat = decimal.Parse(valueStr, NumberStyles.Float, nfi);
                                tagValue.TimeStamp  = Convert.ToDateTime(timeStampStr.Trim());
                                tag.TagValues.Add(tagValue);
                            }
                        }
                    }
                }
                fileStream.Close();
            }
            return(tag);
        }
        public void GetTagKeysAndValues_ReturnsExpected()
        {
            var opts  = new CloudFoundryForwarderOptions();
            var stats = new OpenCensusStats();
            var ep    = new SpringBootMetricWriter(opts, stats);

            IList <ITagKey> keys = new List <ITagKey>()
            {
                TagKey.Create("status"), TagKey.Create("exception"), TagKey.Create("method"), TagKey.Create("uri")
            };
            IList <ITagValue> values = new List <ITagValue>()
            {
                TagValue.Create("v1"), TagValue.Create("v2"), TagValue.Create("v3"), TagValue.Create("v4")
            };

            var result = ep.GetTagKeysAndValues(keys, values);

            Assert.Equal("v1", result["status"]);
            Assert.Equal("v2", result["exception"]);
            Assert.Equal("v3", result["method"]);
            Assert.Equal("v4", result["uri"]);

            // Verify sorted
            var sortedKeys = result.Keys.ToList();

            Assert.Equal("exception", sortedKeys[0]);
            Assert.Equal("method", sortedKeys[1]);
            Assert.Equal("status", sortedKeys[2]);
            Assert.Equal("uri", sortedKeys[3]);

            values = new List <ITagValue>()
            {
                TagValue.Create("v1"), null, null, null
            };

            result = ep.GetTagKeysAndValues(keys, values);
            Assert.Equal("v1", result["status"]);
            Assert.Single(result);

            values = new List <ITagValue>()
            {
                null, TagValue.Create("v2"), null, null
            };

            result = ep.GetTagKeysAndValues(keys, values);
            Assert.Equal("v2", result["exception"]);
            Assert.Single(result);

            values = new List <ITagValue>()
            {
                TagValue.Create("v1"),
            };

            result = ep.GetTagKeysAndValues(keys, values);
            Assert.Empty(result);
        }
Exemplo n.º 12
0
        public void HandleThreadsEvent_RecordsValues()
        {
            var options  = new MetricsEndpointOptions();
            var stats    = new OpenCensusStats();
            var tags     = new OpenCensusTags();
            var observer = new CLRRuntimeObserver(options, stats, tags, null);

            CLRRuntimeSource.ThreadMetrics metrics = new CLRRuntimeSource.ThreadMetrics(100, 100, 200, 200);
            observer.HandleThreadsEvent(metrics);

            var live    = stats.ViewManager.GetView(ViewName.Create("clr.threadpool.active"));
            var aggData = MetricsHelpers.SumWithTags(live) as IMeanData;

            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);

            aggData = MetricsHelpers.SumWithTags(live, new List <ITagValue>()
            {
                TagValue.Create("worker")
            }) as IMeanData;
            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);

            aggData = MetricsHelpers.SumWithTags(live, new List <ITagValue>()
            {
                TagValue.Create("completionPort")
            }) as IMeanData;
            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);

            var avail = stats.ViewManager.GetView(ViewName.Create("clr.threadpool.avail"));

            aggData = MetricsHelpers.SumWithTags(avail) as IMeanData;
            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);

            aggData = MetricsHelpers.SumWithTags(avail, new List <ITagValue>()
            {
                TagValue.Create("worker")
            }) as IMeanData;
            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);

            aggData = MetricsHelpers.SumWithTags(avail, new List <ITagValue>()
            {
                TagValue.Create("completionPort")
            }) as IMeanData;
            Assert.Equal(100, aggData.Mean);
            Assert.Equal(100, aggData.Min);
            Assert.Equal(100, aggData.Max);
        }
        public void TestDeserializeOneTag()
        {
            var output = new MemoryStream();

            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key", "Value", output);
            var expected = tagger.EmptyBuilder.Put(TagKey.Create("Key"), TagValue.Create("Value")).Build();

            Assert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }
Exemplo n.º 14
0
 /// <summary>
 /// Enqueues the specified snapshot value for writing.
 /// </summary>
 /// <param name="tagId">The tag ID.</param>
 /// <param name="value">The tag value.</param>
 internal void WriteValue(Guid tagId, TagValue value)
 {
     _valuesLock.EnterReadLock();
     try {
         _values[tagId] = value;
     }
     finally {
         _valuesLock.ExitReadLock();
     }
 }
Exemplo n.º 15
0
        public void GetKeyForItemTest()
        {
            TagValueCollection_Accessor target = new TagValueCollection_Accessor();
            TagValue item     = new TagValue("Test", TagType.Additive, false);
            string   expected = "Test";
            string   actual;

            actual = target.GetKeyForItem(item);
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 16
0
        public void Invoke_WithMetricsRequest_ReturnsExpected()
        {
            var opts          = new MetricsEndpointOptions();
            var stats         = new OpenCensusStats();
            var tagsComponent = new TagsComponent();
            var tagger        = tagsComponent.Tagger;
            var ep            = new MetricsEndpoint(opts, stats);

            var testMeasure = MeasureDouble.Create("test.total", "test", MeasureUnit.Bytes);

            SetupTestView(stats, Sum.Create(), testMeasure, "test.test1");

            var context1 = tagger
                           .EmptyBuilder
                           .Put(TagKey.Create("a"), TagValue.Create("v1"))
                           .Put(TagKey.Create("b"), TagValue.Create("v1"))
                           .Put(TagKey.Create("c"), TagValue.Create("v1"))
                           .Build();

            long allKeyssum = 0;

            for (var i = 0; i < 10; i++)
            {
                allKeyssum += i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context1);
            }

            var alltags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("a", "v1"),
                new KeyValuePair <string, string>("b", "v1"),
                new KeyValuePair <string, string>("c", "v1")
            };

            var req  = new MetricsRequest("test.test1", alltags);
            var resp = ep.Invoke(req) as MetricsResponse;

            Assert.NotNull(resp);

            Assert.Equal("test.test1", resp.Name);

            Assert.NotNull(resp.Measurements);
            Assert.Single(resp.Measurements);
            var sample = resp.Measurements[0];

            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);
            Assert.Equal(allKeyssum, sample.Value);

            Assert.NotNull(resp.AvailableTags);
            Assert.Equal(3, resp.AvailableTags.Count);

            req  = new MetricsRequest("foo.bar", alltags);
            resp = ep.Invoke(req) as MetricsResponse;
            Assert.Null(resp);
        }
Exemplo n.º 17
0
        public static void readDI(string id)
        {
            while (true)
            {
                DI tag;
                lock (db.DIs)
                {
                    try
                    {
                        tag = DItags[id];
                    }
                    catch
                    {
                        return;
                    }

                    double value;
                    if (tag.OnOffScan)
                    {
                        if (tag.Driver == "SD")
                        {
                            value = SimulationDriver.ReturnValue(tag.Address);
                        }
                        else
                        {
                            value = RealTimeDriver.ReturnValue(tag.Address);
                        }

                        if (value > 0.5)
                        {
                            value = 1;
                        }
                        else
                        {
                            value = 0;
                        }

                        lock (locker)
                        {
                            TagValue tv = new TagValue("DI", tag.Id, dataKeyId, DateTime.Now, value);
                            dataKeyId++;
                            db.TagValues.Add(tv);
                            db.SaveChanges();
                        }


                        trending.write($"DI tag\t ID: {tag.Id}\t VALUE: {value} ");
                    }
                }
                if (tag != null)
                {
                    Thread.Sleep(tag.ScanTime * 1000);
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Notifica a Notiway que un mensaje fue leido
        /// </summary>
        /// <param name="request">Objeto que contiene todos los datos de autenticacion del usuario y el Id del mensaje</param>
        public void NotiwayNewsReadNotification(NotiwayNewsReadNotificationRequest request)
        {
            String _methodName = String.Format("{0}", System.Reflection.MethodBase.GetCurrentMethod().Name);

            LogRequest(request);

            var sessionId = GetSessionId(request, out errorMessage);

            if (errorMessage != ErrorMessagesMnemonics.None)
            {
                return;
            }

            var countryId  = Convert.ToInt32(ConfigurationManager.AppSettings["CountryId"]);
            var platformId = Convert.ToInt32(String.IsNullOrEmpty(request.Platform) ? ConfigurationManager.AppSettings["DefaultPlatform"] : request.Platform);

            if (countryId == 14 && platformId == 1)
            {
                countryId  = 1;
                platformId = 4;
            }

            try
            {
                using (var db = new Movilway.API.Data.Notiway.NotiwayEntities())
                {
                    ProviderLogger.InfoLow(() => TagValue.New()
                                           .MethodName(_methodName)
                                           .Message("[" + sessionId + "] " + "Actualizando registro ...")
                                           );

                    db.Database.ExecuteSqlCommand(
                        QUERY_AUDIT_READ,
                        new SqlParameter("@CountryP", countryId),
                        new SqlParameter("@PlatformP", platformId),
                        new SqlParameter("@LoginP", request.AuthenticationData.Username),
                        new SqlParameter("@ScheduleP", request.ScheduleId),
                        new SqlParameter("@DeviceTypeP", request.DeviceType)
                        );
                }

                ProviderLogger.InfoLow(() => TagValue.New()
                                       .MethodName(_methodName)
                                       .Message("[" + sessionId + "] " + "Hecho")
                                       );
            }
            catch (Exception e)
            {
                ProviderLogger.ExceptionLow(() => TagValue.New()
                                            .MethodName(_methodName)
                                            .Message("[AUDITORIA] [" + sessionId + "] " + "Error actualizando auditoria de mensaje")
                                            .Exception(e)
                                            );
            }
        }
        /// <summary>
        /// Actualiza la informacion de contacto de un agente en el sistema
        /// </summary>
        /// <param name="requestObject"></param>
        /// <param name="kinacuWS"></param>
        /// <param name="sessionID"></param>
        /// <returns></returns>
        /// <returns>Retorna el tipo IMovilwayApiResponse con el respectivo codigo de error y mensaje</returns>
        public override IMovilwayApiResponse PerformKinacuOperation(IMovilwayApiRequest requestObject, KinacuWebService.SaleInterface kinacuWS, string sessionID)
        {
            UpdateContactInfoAgentResponseBody response = new UpdateContactInfoAgentResponseBody();

            try
            {
                if (sessionID.Equals("0"))
                {
                    return new UpdateContactInfoAgentResponseBody()
                           {
                               ResponseCode    = 90,
                               ResponseMessage = "error session",
                               TransactionID   = 0
                           }
                }
                ;

                UpdateContactInfoAgentRequestBody request = requestObject as UpdateContactInfoAgentRequestBody;

                logger.InfoLow(() => TagValue.New().Message("[API] " + base.LOG_PREFIX + "[UpdateContactInfoAgentProvider]").Tag("[RCV-DATA] UpdateContactInfoAgentProviderParameters ").Value(request));

                var result = Utils.ChangeBranchContactInfo(request.AgeId.ToString(), request.Email, request.Phone);

                if (result)
                {
                    response = new UpdateContactInfoAgentResponseBody
                    {
                        ResponseCode    = 0,
                        ResponseMessage = "Exito",
                        TransactionID   = new Random().Next(10000000, 99999999)
                    }
                }
                ;
                else
                {
                    response = new UpdateContactInfoAgentResponseBody
                    {
                        ResponseCode    = 99,
                        ResponseMessage = _GenericError
                    }
                };
            }
            catch (Exception ex)
            {
                //cambiar error general erro inesperado
                response.ResponseCode    = 500;
                response.ResponseMessage = _GenericError;
                response.TransactionID   = 0;
                string mensaje = String.Concat("[API] " + base.LOG_PREFIX + "[UpdateContactInfoAgentProvider] ", ". Exception: ", ex.Message, ". ", ex.StackTrace);
                logger.ErrorLow(mensaje);
            }

            logger.InfoLow(() => TagValue.New().Message("[API] " + base.LOG_PREFIX).Tag("[UpdateContactInfoAgentProviderResult]").Value(response));
            return(response);
        }
Exemplo n.º 20
0
        public static string ToKey(this TagValue tagValue)
        {
            string key = null;

            if (tagValue != null)
            {
                key = string.Format("{0}.{1}", tagValue.Id_Prensa, (int)tagValue.Type);
            }

            return(key);
        }
Exemplo n.º 21
0
 /// <summary>
 /// Escribe en log los datos de la respuesta
 /// </summary>
 /// <param name="response">Base request object</param>
 protected void LogResponse(object response)
 {
     try
     {
         this.ProviderLogger.CheckPointLow(() => TagValue.New().Tag("Response").Value(response));
     }
     catch (Exception e)
     {
         this.ProviderLogger.ExceptionLow(() => TagValue.New().Message("Exception trying to log the Response").Exception(e));
     }
 }
Exemplo n.º 22
0
 /// <summary>
 /// Creates a new <see cref="RedisTagValue"/> from a standard Aika <see cref="TagValue"/>.
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 internal static RedisTagValue FromTagValue(TagValue value)
 {
     return(new RedisTagValue()
     {
         UtcSampleTime = value.UtcSampleTime,
         NumericValue = value.NumericValue,
         TextValue = value.TextValue,
         Quality = (int)value.Quality,
         Units = value.Units
     });
 }
Exemplo n.º 23
0
            public TagValue GetTagValue(string tag_value)
            {
                TagValue tv;

                if (tag_values.TryGetValue(tag_value, out tv) == false)
                {
                    tv = new TagValue(vfs);
                    tag_values[tag_value] = tv;
                }
                return(tv);
            }
Exemplo n.º 24
0
        /// <summary>
        /// Obtiene la respuesta en base a la petición realizada por Http o Https
        /// </summary>
        /// <param name="request">Petición a realizar</param>
        /// <returns>Devuelve el contenido de la página</returns>
        public static string GetResponse(Request request)
        {
            string methodName  = string.Format("{0}", System.Reflection.MethodBase.GetCurrentMethod().Name);
            string pageContent = string.Empty;

            HttpWebRequest baseRequest = HttpUtils.BuildHttpRequest(request);

            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)baseRequest.GetResponse();
                Stream          responseStream  = httpWebResponse.GetResponseStream();

                if (!request.AutomaticDecompression)
                {
                    if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                    {
                        responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    }
                    else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                    {
                        responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    }
                }

                StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
                pageContent = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                httpWebResponse.Close();

                if (request.HandleAutomaticRedirect && (
                        httpWebResponse.StatusCode == HttpStatusCode.Redirect ||
                        httpWebResponse.StatusCode == HttpStatusCode.TemporaryRedirect ||
                        (httpWebResponse.StatusCode == HttpStatusCode.Found &&
                         httpWebResponse.Headers.AllKeys.Contains("Location"))))
                {
                    request.Url = httpWebResponse.Headers["Location"].Contains(request.Host) ? httpWebResponse.Headers["Location"]
                        : ((httpWebResponse.Headers["Location"].ToLower().StartsWith("http") || httpWebResponse.Headers["Location"].ToLower().StartsWith("https")) ? httpWebResponse.Headers["Location"] : request.Host + (string.IsNullOrEmpty(request.BasePath) ? string.Empty : request.BasePath) + httpWebResponse.Headers["Location"]);
                    request.Method      = HttpUtils.Get;
                    request.ContentType = String.Empty;

                    //request.Host = "www1.sucursalelectronica.com";
                    pageContent = GetResponse(request);
                }
            }
            catch (Exception ex)
            {
                Logger.ExceptionLow(() => TagValue.New()
                                    .MethodName(methodName)
                                    .Exception(ex));
            }

            return(pageContent);
        }
Exemplo n.º 25
0
        public void TestTagValueEquals()
        {
            var v1 = TagValue.Create("foo");
            var v2 = TagValue.Create("foo");
            var v3 = TagValue.Create("bar");

            Assert.Equal(v1, v2);
            Assert.NotEqual(v1, v3);
            Assert.NotEqual(v2, v3);
            Assert.Equal(v3, v3);
        }
Exemplo n.º 26
0
        public void Create_AllowTagValueWithMaxLength()
        {
            char[] chars = new char[TagValue.MAX_LENGTH];
            for (int i = 0; i < chars.Length; i++)
            {
                chars[i] = 'v';
            }
            String value = new String(chars);

            Assert.Equal(value, TagValue.Create(value).AsString);
        }
Exemplo n.º 27
0
        public void Create_DisallowTagValueOverMaxLength()
        {
            char[] chars = new char[TagValue.MAX_LENGTH + 1];
            for (int i = 0; i < chars.Length; i++)
            {
                chars[i] = 'v';
            }
            String value = new String(chars);

            Assert.Throws <ArgumentOutOfRangeException>(() => TagValue.Create(value));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Paso llamado método TopUp con el producto de CashIn, para que el protocolo realice el llamado
        /// de constitución y emisión en el WS de MultiPay 472
        /// </summary>
        /// <param name="request">Objeto que contiene la información del giro</param>
        /// <param name="idGiro">ID del giro creado en base de datos MW</param>
        /// <param name="sessionId">ID de sesión para poner en los mensajes de log</param>
        /// <param name="exc">Excepción generada al llamar el método del API</param>
        /// <returns>Respuesta del TopUp</returns>
        private DataContract.TopUpResponseBody EmitirPaso2(EmitirRequest request, int idGiro, string sessionId, out Exception exc)
        {
            string methodName = string.Format("{0}", System.Reflection.MethodBase.GetCurrentMethod().Name);

            exc = null;

            DataContract.TopUpResponseBody resp = null;
            string endpointName = "TopUp";

            try
            {
                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Llamando método \"" + endpointName + "\" ..."));

                resp = new ServiceExecutionDelegator <DataContract.TopUpResponseBody, DataContract.TopUpRequestBody>().ResolveRequest(
                    new DataContract.TopUpRequestBody()
                {
                    AuthenticationData = new AuthenticationData()
                    {
                        Username = request.AuthenticationData.Username,
                        Password = request.AuthenticationData.Password
                    },
                    DeviceType = request.DeviceType,
                    Platform   = request.Platform,
                    WalletType = DataContract.WalletType.Stock,
                    ExternalTransactionReference = sessionId,
                    Amount     = request.ValorRecibido,
                    TerminalID = request.Pdv,
                    Recipient  = idGiro.ToString(),
                    MNO        = this.multipayTopUpMno
                },
                    ApiTargetPlatform.Kinacu,
                    ApiServiceName.TopUp);

                this.ProviderLogger.InfoLow(() => TagValue.New()
                                            .MethodName(methodName)
                                            .Message("[" + sessionId + "] " + "Respuesta método \"" + endpointName + "\"")
                                            .Tag("ResponseCode").Value(resp != null && resp.ResponseCode.HasValue ? resp.ResponseCode.Value.ToString() : "NULL")
                                            .Tag("ResponseMessage").Value(resp != null && !string.IsNullOrEmpty(resp.ResponseMessage) ? resp.ResponseMessage : "vacío"));
            }
            catch (Exception ex)
            {
                this.ProviderLogger.ExceptionLow(() => TagValue.New()
                                                 .MethodName(methodName)
                                                 .Message("[" + sessionId + "] " + "Error llamando método \"" + endpointName + "\"")
                                                 .Exception(ex));
                this.errorMessage = ErrorMessagesMnemonics.ApiMethodException;
                exc = ex;
            }

            return(resp);
        }
Exemplo n.º 29
0
        public void TestDeserializeDuplicateTags()
        {
            MemoryStream output = new MemoryStream();

            output.WriteByte(SerializationUtils.VERSION_ID);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key1", "Value1", output);
            ITagContext expected =
                tagger.EmptyBuilder.Put(TagKey.Create("Key1"), TagValue.Create("Value1")).Build();

            Assert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Retorna una lista de IPNetwork con local host y la ip del servidor
        /// </summary>
        /// <param name="FILE_IPS_PATH"></param>
        /// <returns></returns>
        private static HashSet <IPNetWork> FactoryMethod(string FILE_IPS_PATH)
        {
            HashSet <IPNetWork> result = new HashSet <IPNetWork>();

            try
            {
                IPNetWork network = IPNetWork.Parse("127.0.0.1");
                result.Add(network);

                IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                if (ipEntry.AddressList.Length > 0)
                {
                    IPAddress IP = ipEntry.AddressList[ipEntry.AddressList.Length - 1];
                    result.Add(IPNetWork.Parse(IP.ToString()));
                }



                // Read the file and display it line by line.
                using (System.IO.StreamReader file = new System.IO.StreamReader(FILE_IPS_PATH, System.Text.Encoding.Default))
                {
                    string line = null;
                    while ((line = file.ReadLine()) != null)
                    {
                        try
                        {
                            line = line.Trim().Replace(" ", "");
                            if (line[0] != '!' && line[0] != '-')
                            {
                                network = IPNetWork.Parse(line);
                                result.Add(network);
                            }
                        }
                        catch (ArgumentException ex)
                        {
                            logger.InfoHigh(() => TagValue.New().Tag("[ERROR IP ARCHIVO H2H]").Value(line));
                        }
                        catch (Exception ex)
                        {
                            logger.InfoHigh(() => TagValue.New().Tag("[ERROR INESPERADO IP DE ARCHIVO]").Value(line));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MANEJO DE ERROR SI NO SE PUDO CARGAR LA LISTA DE IPS
                logger.InfoHigh(() => TagValue.New().Tag("ERROR INESPERADO CARGANDO IP'S H2H").Exception(ex));
            }

            return(result);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Writes values into the archive.
        /// </summary>
        /// <param name="tagId">The tag ID.</param>
        /// <param name="values">The values to write.</param>
        /// <returns>
        /// The results of the write.
        /// </returns>
        internal WriteTagValuesResult InsertArchiveValues(string tagId, IEnumerable <TagValue> values)
        {
            var rawData = _archive.GetOrAdd(tagId, x => new RawDataSet());
            var tag     = _tags[tagId];

            rawData.Lock.EnterWriteLock();
            try {
                var latestValue = rawData.LastOrDefault().Value;

                var      firstValueToInsert = values.First();
                TagValue lastValueToInsert  = null;
                var      notes = new List <string>();

                if (latestValue != null && firstValueToInsert.UtcSampleTime <= latestValue.UtcSampleTime)
                {
                    lastValueToInsert = values.Last();

                    // Remove any existing samples where the sample time is inside the time range in the values being inserted.

                    var keysToRemove = rawData.Keys.Where(x => x >= firstValueToInsert.UtcSampleTime && x <= lastValueToInsert.UtcSampleTime).ToArray();
                    foreach (var key in keysToRemove)
                    {
                        rawData.Remove(key);
                    }

                    notes.Add($"Removed {keysToRemove.Length} existing samples inside the insertion time range.");
                }

                int insertedSampleCount = 0;

                foreach (var item in values)
                {
                    ++insertedSampleCount;
                    rawData.Add(item.UtcSampleTime, item);
                    if (lastValueToInsert == null || item.UtcSampleTime > lastValueToInsert.UtcSampleTime)
                    {
                        lastValueToInsert = item;
                    }
                }

                return(new WriteTagValuesResult(true, insertedSampleCount, firstValueToInsert.UtcSampleTime, lastValueToInsert.UtcSampleTime, notes));
            }
            finally {
                tag.Properties["Sample Count"] = rawData.Count;
                if (rawData.Count > 0)
                {
                    tag.Properties["Earliest Sample Time"] = rawData.Keys.First().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                    tag.Properties["Latest Sample Time"]   = rawData.Keys.Last().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                }
                rawData.Lock.ExitWriteLock();
            }
        }
Exemplo n.º 32
0
            internal Tag(string name, TagValue value) {
                _name = name;
                _value = value;

                if (_name[_name.Length - 1] == '*') {
                    _prefixLength = _name.Length - 1;
                }
                else {
                    _prefixLength = -1;
                }
            }
Exemplo n.º 33
0
 public void TagEmptyValueConstructorTest()
 {
     TagValue target = new TagValue(String.Empty, TagType.Additive, false);
 }
Exemplo n.º 34
0
 public void TagNullValueConstructorTest()
 {
     TagValue target = new TagValue(null, TagType.Additive, false);
 }
Exemplo n.º 35
0
        public void CookedValueTest()
        {
            TagValue target = new TagValue("Test", TagType.Additive, false);
            target.SetCookedValue("-Test");
            Assert.AreEqual("Test", target.Value);
            Assert.AreEqual(TagType.Subtractive, target.Type);

            target.SetCookedValue("Test");
            Assert.AreEqual("Test", target.Value);
            Assert.AreEqual(TagType.Additive, target.Type);

            target.SetCookedValue("-Test");
            target.SetCookedValue("+Test");
            Assert.AreEqual("Test", target.Value);
            Assert.AreEqual(TagType.Additive, target.Type);
        }
Exemplo n.º 36
0
 public void EmptyValueTest()
 {
     TagValue target = new TagValue(String.Empty, TagType.Additive, false); 
 }
Exemplo n.º 37
0
 public void WhitespaceValueTest()
 {
     TagValue target = new TagValue("Test", TagType.Additive, false);
     target.Value = " ";
 }
Exemplo n.º 38
0
 public void NullValueTest()
 {
     TagValue target = new TagValue(null, TagType.Additive, false);
 }
Exemplo n.º 39
0
        public void SerializationCurrentVersion()
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            
            string value = "Test";
            TagType type = TagType.Additive; 
            bool isUser = false; 
            TagValue target = new TagValue(value, type, isUser);

            StringWriter stringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(stringWriter, settings);
            var serial = new XmlSerializer(typeof(TagValue));

            serial.Serialize(writer, target);

            string xml = @"<?xml version=""1.0"" encoding=""utf-16""?><TagValue Version=""1""><Value>+Test</Value></TagValue>";
            Assert.AreEqual(xml, stringWriter.ToString());
        }
Exemplo n.º 40
0
 public void IsUserTagTest()
 {
     TagValue target = new TagValue("Test", TagType.Additive, false); 
     Assert.AreEqual(false, target.IsUserTag);
     target.IsUserTag = true;
     Assert.AreEqual(true, target.IsUserTag);
 }
Exemplo n.º 41
0
 public void TagWhitespaceValueConstructorTest()
 {
     TagValue target = new TagValue(" ", TagType.Additive, false);
 }
        public void WriteXmlTest()
        {
            XmlWriterSettings settings = new XmlWriterSettings();

            string value = "Test";
            TagType type = TagType.Additive;
            bool isUser = false;
            TagValue firstItem = new TagValue(value, type, isUser);

            StringWriter stringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(stringWriter, settings);
            var serial = new XmlSerializer(typeof(TagValueCollection));

            var coll = new TagValueCollection();
            coll.Add(firstItem);

            serial.Serialize(writer, coll);
            Assert.AreEqual(m_1ItemXml, stringWriter.ToString());

            coll.Add(new TagValue("AnotherTestValue", TagType.Additive, false));
            stringWriter = new StringWriter();
            writer = XmlWriter.Create(stringWriter, settings);
            serial.Serialize(writer, coll);
            Assert.AreEqual(m_2ItemXml, stringWriter.ToString());
        }
 public void GetKeyForItemTest()
 {
     TagValueCollection_Accessor target = new TagValueCollection_Accessor();
     TagValue item = new TagValue("Test", TagType.Additive, false);
     string expected = "Test";
     string actual;
     actual = target.GetKeyForItem(item);
     Assert.AreEqual(expected, actual);
 }