Error() public static method

public static Error ( string format ) : void
format string
return void
Exemplo n.º 1
0
       /// <summary>
       /// Parses unsigned constant values. Parses hex, oct, bin and exponent values as well.
       /// </summary>
       /// <param name="val">The string value to convert from. It can be hex, oct, bin, or nnnExx</param>
        /// <param name="maxBitSize"></param>
        /// <param name="paramNo">The parameter place for logging errors. </param>
        /// <param name="log"></param>
       /// <returns></returns>
        internal static uint parseUnSignedNumber(string val, int maxBitSize, int paramNo, Log log)
        {
            Match m = Regex.Match(val, RegexRecognizers.UnSignedNumber);

            if (!m.Groups[2].Success)
            {
                log.Error("param {0}: unable to recognize constant '{1}'", paramNo, val);
                return 0;
            }

            char opType = m.Groups[1].Value[0];
            string opVal = m.Groups[2].Value;

            if (opVal == "")
                log.Error("param {0}: compiler error 4360 '{1}'", paramNo, val);

            uint num;
            if (opType > '0' && opType <= '9')
                num = UInt32.Parse(opVal, NumberStyles.AllowLeadingSign | NumberStyles.AllowExponent);
            else // if (opType == 'x' || opType == 'o' || opType == 'b')
                num = Convert.ToUInt32(opVal, (opType == 'x') ? 16 : (opType == 'o') ? 8 : 2);

            if (num > ((1 << maxBitSize) - 1))
            {
                log.Error("param {0}: The value '{1}' will not fit in {2} bits", paramNo, val, maxBitSize);
                num &= (uint)((1 << maxBitSize) - 1);
            }

            return num;
        }
        /// <inheritdoc />
        /// <summary>
        /// Checks if we can handle/store the given asset pair. Also, writes an error to log according to timeout from settings.
        /// </summary>
        /// <param name="assetPairId">Asset pair ID.</param>
        /// <returns>True if repository is able to store such a pair, and false otherwise.</returns>
        public override bool CanHandleAssetPair(string assetPairId)
        {
            if (base.CanHandleAssetPair(assetPairId))
            {
                return(true); // It's Ok, we can store this asset pair
            }
            // If we can't store and need to notify others...
            var needToLog = false;

            if (!_knownUnsupportedAssetPairs.TryGetValue(assetPairId, out var lastLogMoment))
            {
                _knownUnsupportedAssetPairs.Add(assetPairId, _clock.UtcNow);
                needToLog = true;
            }
            else
            {
                if (_clock.UtcNow.Subtract(lastLogMoment) > _notificationTimeout)
                {
                    needToLog = true;
                    _knownUnsupportedAssetPairs[assetPairId] = _clock.UtcNow;
                }
            }

            if (needToLog)
            {
                Log?.Error(nameof(CanHandleAssetPair),
                           new ArgumentOutOfRangeException("Incomptible candle batch recieved: connection string for asset pair not configured. Skipping..."),
                           context: assetPairId);
            }

            return(false); // Finally
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a table 
        /// e.g. DDL.CreateTable( "Sample", "col1,int,col2,int,col3,varchar(10),col4,int,col5,int");
        /// </summary>
        /// <param name="sTableName"></param> - Name of the new table
        /// <param name="sColumns_i"></param> - A string containing list of colums in the format Column1,datatype,
        ///                                     Column2,datatype...etc
        public static void CreateTable(string sTableName, string sColumns_i)
        {
            using (Log log = new Log(".::()"))
            {
                try
                {

                    string sQuerry = "CREATE TABLE " + sTableName + "(";
                    string[] sColums = Strings.Split(sColumns_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sColums[0] + " " + sColums[1];

                    for (int nIndex = 2; nIndex < sColums.Length; nIndex += 2)
                        sQuerry = sQuerry + "," + sColums[nIndex] + " " + sColums[nIndex + 1];

                    sQuerry += ")";

                    DBWrapper.ExecuteNonQueryEx(sQuerry);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
Exemplo n.º 4
0
 public override bool Validate(IISWebArguments current, MainArguments main)
 {
     if (!base.Validate(current, main))
     {
         return(false);
     }
     if (!string.IsNullOrEmpty(current.SSLPort))
     {
         if (int.TryParse(current.SSLPort, out var port))
         {
             if (port < 1 || port > 65535)
             {
                 Log?.Error("Invalid --{param}, value should be between 1 and 65535", SslPortParameterName);
                 return(false);
             }
         }
         else
         {
             Log?.Error("Invalid --{param}, value should be a number", SslPortParameterName);
             return(false);
         }
     }
     if (!string.IsNullOrEmpty(current.SSLIPAddress))
     {
         if (!IPAddress.TryParse(current.SSLIPAddress, out _))
         {
             Log?.Error("Invalid --{sslipaddress}", SslIpParameterName);
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 5
0
        public bool Initialize()
        {
            string methoName = MethodBase.GetCurrentMethod().Name;

            try
            {
                smtp = new SmtpClient();


                smtp.Host                  = settings.Host;
                smtp.Port                  = settings.Port;
                smtp.EnableSsl             = settings.Ssl;
                smtp.Timeout               = 20 * 1000;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                if (settings.UseCredential)
                {
                    smtp.Credentials = new System.Net.NetworkCredential(settings.EmailAddress, settings.Password);
                }


                IsInitialized = true;
            }
            catch (Exception ex)
            {
                Log?.Error(className, methoName, ex.ToString());
                IsInitialized = false;
            }

            return(IsInitialized);
        }
Exemplo n.º 6
0
 public static void Main(string[] args)
 {
     Configuration config = Configuration.LoadConfiguration("settings.json");
     Log mainLog = new Log (config.MainLog, null);
     //byte counter = 0;
     foreach (Configuration.BotInfo info in config.Bots)
     {
         //Console.WriteLine("--Launching bot " + info.DisplayName +"--");
         mainLog.Info ("Launching Bot " + info.DisplayName + "...");
         new Thread(() =>
         {
             int crashes = 0;
             while (crashes < 1000)
             {
                 try
                 {
                     new Bot(info, config.ApiKey);
                 }
                 catch (Exception e)
                 {
                     mainLog.Error ("Error With Bot: "+e);
                     crashes++;
                 }
             }
         }).Start();
         Thread.Sleep(5000);
     }
 }
        private void DisconnectAllClientChannels()
        {
            try
            {
                Log?.Information(className, "DisconnectAllClientChannels", "Disconnecting clients");


                //var channels = ClientChannelManager?.Channels.Keys.ToArray();
                //foreach (var channel in channels)
                //{
                //    try
                //    {
                //        channel.CloseAsync();
                //    }
                //    catch (Exception ex)
                //    {
                //        Logging.ServerChannelLogger.Instance.Log.Error(className, "DisconnectAllClientChannels",
                //            string.Format("Message: {0}, Details: {1}", ex.Message, ex.ToString()));
                //    }
                //}
            }
            catch (Exception ex)
            {
                Log?.Error(className, "DisconnectAllClientChannels",
                           string.Format("Message: {0}, Details: {1}", ex.Message, ex.ToString()));
            }
        }
Exemplo n.º 8
0
        public static Window AboutWindow(Application application, Log log)
        {
            const string prefix = "Dialogs - AboutWindow";
            if ((application == null) || application.HasExited)
            {
                throw new RegressionTestFailedException(prefix + ": Application does not exist or has already exited.");
            }

            // Note that the windows can't be found through an Automation ID for some reason, hence
            // using the title of the window.
            var mainWindow = MainWindow(application, log);
            if (mainWindow == null)
            {
                return null;
            }

            return Retry.Times(
                () =>
                {
                    log.Debug(prefix, "Trying to get the about window.");

                    var window = mainWindow.ModalWindow("About");
                    if (window == null)
                    {
                        log.Error(prefix, "Failed to get the about window.");
                    }

                    return window;
                });
        }
Exemplo n.º 9
0
        public bool SendMessage(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return(false);
            }
            if (!_tcpClient.Connected)
            {
                return(false);
            }

            var strm   = _tcpClient.GetStream();
            var writer = new StreamWriter(strm)
            {
                AutoFlush = true
            };

            try
            {
                if (_tcpClient.Connected)
                {
                    writer.WriteLine(msg);
                }

                return(true);
            }
            catch (Exception ex)
            {
                SendFailed?.Invoke(this, ex);
                Log?.Error("SendMessage failed", ex);
                return(false);
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            var log = new Log();
            log.Info("Startup");

            var servers = new List<ServerInfo>();

            using (var dc = new Arma3BeClientContext())
            {
                servers = dc.ServerInfo.Where(x => x.Active).ToList();
            }

            var models = servers.Select(x=>OpenServerInfo(x, log)).ToList();

            while (true)
            {
                try
                {
                    var t = Task.Run(() => run(models));
                    t.Wait();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
Exemplo n.º 11
0
        public async Task HandleLines()
        {
            try
            {
                var strm = _tcpClient.GetStream();
                using (StreamReader reader = new StreamReader(strm, Encoding.UTF8))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        LineReceived?.Invoke(this, line);
                    }
                }
            }
            catch (IOException ex)
            {
                Log?.Error("HandleLines::IOException", ex);
            }
            catch (InvalidOperationException ex)
            {
                Log?.Error("HandleLines::InvalidOperationException", ex);
            }

            await Task.Delay(1000);
        }
Exemplo n.º 12
0
        private async Task SetTabAsync(
            Type selectedTabType)
        {
            if (!IsTab(selectedTabType))
            {
                return;
            }


            var tabbedPage = RootPage as TabbedPage;

            await Device.InvokeOnMainThreadAsync(() =>
            {
                var tab = tabbedPage
                          .Children
                          .FirstOrDefault(tab => IsPageOfType(
                                              tab,
                                              selectedTabType));

                if (tab == null)
                {
                    Log?.Error(
                        $"{tabbedPage.GetType().Name} does not contain requested view {selectedTabType.Name}!");

                    return;
                }


                tabbedPage.CurrentPage = tab;
            });
        }
Exemplo n.º 13
0
        private void DpOnModified(object sender)
        {
            var dp = sender as DataProvider;

            if (dp == null)
            {
                return;
            }

            if (Router == null)
            {
                Log?.Error("Error: router is not set");
                return;
            }

            var obj = dp.ToJson();

            if (obj == null)
            {
                Log?.Error("Error: data object is null");
                return;
            }

            Router.SendBroadcast(obj, dp.Mode);
        }
Exemplo n.º 14
0
        // TODO - Define a margin to move time and review possible tamper scenarios
        private DateTime GetUtc()
        {
            DateTime? antiBack  = null;
            DateTime? reliable  = null;
            Exception exception = null;

            try
            {
                reliable = ReliableTimeProvider.UtcNow();
                Log?.Info("Reliable provider get time successfully");
                AntiBackTimeProvider.SetValue(reliable.Value);
            }
            catch (Exception ex)
            {
                exception = ex;
                Log?.Error($"Error '{ex.GetType().Name}' in ReliableTimeProvider: {ex.Message}", ex);
            }
            try
            {
                antiBack = AntiBackTimeProvider.UtcNow();
                Log?.Info("Anti-back provider get time successfully");
            }
            //catch (NoStoredTimeValueException nstvex) { exception = nstvex; }
            //catch (BackTimeException btex) { exception = btex; }
            catch (Exception ex)
            {
                exception = ex;
                Log?.Error($"Error '{ex.GetType().Name}' in AntiBackProvider: {ex.Message}", ex);
            }
            if (reliable != null || antiBack != null)
            {
                return((reliable ?? antiBack).Value);
            }
            throw new TamperedTimeException(exception);
        }
Exemplo n.º 15
0
        /// <summary>开始工作</summary>
        /// <param name="reason"></param>
        protected virtual void StartWork(String reason)
        {
            // 依赖服务检测
            this.PreStartWork();

            var tcount = ThreadCount;
            var sch    = Schedule;
            var count  = tcount + sch.Count;

            WriteLog("服务启动 共[{0:n0}]个工作线程 {1}", count, reason);

            try
            {
                var ss = Items = new ServiceItem[count];

                // 可以通过设置任务的时间间隔小于0来关闭指定任务
                var vs = Intervals;
                for (var i = 0; i < count; i++)
                {
                    var time = vs[0];
                    // 使用专用的时间间隔
                    if (i < vs.Length)
                    {
                        time = vs[i];
                    }

                    var si = ss[i] = new ServiceItem(i, null, time);
                    if (i < tcount)
                    {
                        si.Callback = Work;
                    }
                    else
                    {
                        var job = sch.Jobs[i - tcount];
                        if (job is JobBase jb)
                        {
                            jb.Log = Log;
                        }
                        si.Job = job;
                    }

                    //StartWork(i);
                    ss[i].Start(reason);
                }

                // 启动服务管理线程
                StartManagerThread();

                //// 显示用户界面交互窗体
                //Interactive.ShowForm();
            }
            catch (Exception ex)
            {
                //WriteLog(ex.ToString());
                Log?.Error(ex.GetTrue()?.ToString());
            }
        }
Exemplo n.º 16
0
 private static void LogMessagesTo(TraceSource traceSource)
 {
     var log = new Log(traceSource);
     log.Verbose(_verboseMessage);
     log.Information(_infoMessage);
     log.Warning(_warningMessage);
     log.Error(_errorMessage);
     traceSource.Flush();
 }
Exemplo n.º 17
0
        private IChannelHandler CreateChannelHandler()
        {
            IChannelHandler channelHandler = null;

            try
            {
                channelHandler = new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (configuration.EnableTls)
                    {
                        X509Certificate2 cert = GetCertificate();
                        if (cert != null)
                        {
                            targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
                            if (string.IsNullOrEmpty(targetHost))
                            {
                                RaiseError(null, ErrorMessages.Message(ErrorType.TargetHostDnsNameNotFound),
                                           ErrorType.TargetHostDnsNameNotFound);
                                throw new NullReferenceException(ErrorMessages.Message(ErrorType.TargetHostDnsNameNotFound));
                            }

                            TlsHandlerFactory tlsFactory = new TlsHandlerFactory();
                            TlsHandler tlsHandler        = tlsFactory.CreateStandardTlsHandler(targetHost);
                            pipeline.AddLast("tls", tlsHandler);
                            //pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                            //}
                        }
                        else
                        {
                            RaiseError(null, ErrorMessages.Message(ErrorType.NoCertificateFoundWhenTlsEnabled),
                                       ErrorType.NoCertificateFoundWhenTlsEnabled);
                            throw new NullReferenceException(ErrorMessages.Message(ErrorType.NoCertificateFoundWhenTlsEnabled));

                            // add intialization error here
                        }
                    }

                    pipeline.AddLast("encoder", encoder);
                    pipeline.AddLast("decoder", decoder);

                    handler                      = new ChannelHandler();
                    handler.ChannelKey           = configuration.ChannelKey;
                    handler.ClientChannelHandler = ClientChannelHandler;
                    pipeline.AddLast("echo", handler);
                });
            }
            catch (Exception ex)
            {
                channelHandler = null;
                Log?.Error(className, "CreateChannelHandler", ex.ToString());
            }

            return(channelHandler);
        }
Exemplo n.º 18
0
        private async Task ProcessMessage(FtpCommand command)
        {
            FtpResponse response;

            Log?.Trace(command);
            var result = FindCommandHandler(command);

            if (result != null)
            {
                var handler         = result.Item2;
                var handlerCommand  = result.Item1;
                var isLoginRequired = result.Item3;
                if (isLoginRequired && !Data.IsLoggedIn)
                {
                    response = new FtpResponse(530, "Not logged in.");
                }
                else
                {
                    try
                    {
                        var cmdHandler  = handler as FtpCommandHandler;
                        var isAbortable = cmdHandler?.IsAbortable ?? false;
                        if (isAbortable)
                        {
                            var newBackgroundTask = Data.BackgroundCommandHandler.Execute(handler, handlerCommand);
                            if (newBackgroundTask != null)
                            {
                                _activeBackgroundTask = newBackgroundTask;
                                response = null;
                            }
                            else
                            {
                                response = new FtpResponse(503, "Parallel commands aren't allowed.");
                            }
                        }
                        else
                        {
                            response = await handler.Process(handlerCommand, _cancellationTokenSource.Token);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log?.Error(ex, "Failed to process message ({0})", command);
                        response = new FtpResponse(501, "Syntax error in parameters or arguments.");
                    }
                }
            }
            else
            {
                response = new FtpResponse(500, "Syntax error, command unrecognized.");
            }
            if (response != null)
            {
                await WriteAsync(response, _cancellationTokenSource.Token);
            }
        }
Exemplo n.º 19
0
        private static void ThrowNotRegisteredException <TViewModel>()
        {
            // todo: which exception type fits best?
            var notRegisteredException = new InvalidOperationException(
                $"There is no reference from viewmodel type {typeof(TViewModel).Name} to a page.");

            Log?.Error(notRegisteredException);


            throw notRegisteredException;
        }
Exemplo n.º 20
0
 public void SetValue(DateTime value)
 {
     foreach (var s in providers)
     {
         try
         {
             s.SaveUtcTime(value);
         }
         catch (Exception ex) { Log?.Error($"Error '{ex.GetType().Name}' saving storage: {ex.Message}", ex); }
     }
 }
Exemplo n.º 21
0
 protected void Application_Error(object sender,EventArgs e)
 {
     ILog _log = new Log();
     StringBuilder content = new StringBuilder();
     HttpRequest request = HttpContext.Current.Request;
     content.AppendFormat("\r\nNavigator:{0}", request.UserAgent);
     content.AppendFormat("\r\nIp:{0}", request.UserHostAddress);
     content.AppendFormat("\r\nUrlReferrer:{0}", request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "");
     content.AppendFormat("\r\nRequest:{0}", Utils.GetRequestValues(request));
     content.AppendFormat("\r\nUrl:{0}", request.Url.AbsoluteUri);
     _log.Error(content.ToString(), Server.GetLastError().GetBaseException());//记录日志
 }
Exemplo n.º 22
0
        public async Task StartAsync()
        {
            string methodName = MethodBase.GetCurrentMethod().Name;

            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();

            var encoder = new StringEncoder();
            var decoder = new StringDecoder();

            try
            {
                bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (configuration.EnableTls)
                    {
                        X509Certificate2 tlsCertificate = GetCertificate();
                        if (tlsCertificate != null)
                        {
                            pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                        }
                        else
                        {
                            Log?.Error(className, methodName, "Certificate not found");
                        }
                    }


                    pipeline.AddLast("encoder", encoder);
                    pipeline.AddLast("decoder", decoder);

                    handler = new ServerChannelHandler();
                    //handler.ClientChannelManager = ClientChannelManager;
                    handler.ChannelHandler = ServerChannelHandler;
                    handler.Log            = Log;

                    pipeline.AddLast("handler", handler);
                }));

                boundChannel = await bootstrap.BindAsync(configuration.Port);
            }
            catch (Exception ex)
            {
                Log?.Error(className, methodName, ex.ToString());
            }
        }
Exemplo n.º 23
0
        public async Task InitializeSchedule()
        {
            if (!Enabled)
            {
                return;
            }

            var type = GetJobObjectType();

            if (type == null)
            {
                Log?.Error($"Job \"{Name}\" cannot be instantiated.");
                return;
            }

            if (_jobInstance == null)
            {
                _jobInstance = Activator.CreateInstance(type) as IJob;
            }

            while (Repeatable)
            {
                var timeSchedule = GetTimeSchedule();
                if (timeSchedule == null)
                {
                    if (!await ExecuteJobAndContinue())
                    {
                        return;
                    }
                }
                else
                {
                    var difference = timeSchedule.TimeNow.TimeOfDay - timeSchedule.Value.TimeOfDay;

                    if (0 <= difference.TotalSeconds && difference.TotalSeconds < RepetitionIntervalTime)
                    {
                        if (!await ExecuteJobAndContinue())
                        {
                            return;
                        }
                    }
                }

                if (RepetitionIntervalTime > 0)
                {
                    //Thread.Sleep(RepetitionIntervalTime * 1000);
                    await Task.Delay(RepetitionIntervalTime * 1000);
                }
            }

            // else !Repeatable
            await ExecuteJobAndContinue();
        }
        /// <inheritdoc cref="INavigationService.CloseModalAsync" />
        public virtual async Task CloseModalAsync <TViewModel>()
        {
            if (Navigation == null)
            {
                Log?.Error(
                    $"'{nameof(Navigation)}' is null!");
                return;
            }


            await Navigation.PopModalAsync(
                animated : Configuration.UseAnimations);
        }
Exemplo n.º 25
0
        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// 处理错误
        /// </summary>
        /// <param name="e"></param>
        protected void DealError(Exception e)
        {
            Log log = new Log(typeof(BllBase));
            log.Error(e);
            //DateTime dt = DateTime.Now;
            //string errorLogName = String.Format("{0}{1}_Error.txt", APPLICATION_ERROR_PATH, dt.ToString("yyyyMMdd"));

            //using (StreamWriter sw = new StreamWriter(errorLogName, true, Encoding.GetEncoding("gb2312")))
            //{
            //    sw.WriteLine(String.Format("[{0}]{1}\r\n"
            //        , dt.ToString("HH:mm:hh")
            //        , e.ToString()));
            //}
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            Log log = new Log();

            Migrator migrator = null;
            AbstractParser parser = null;

            try
            {
                parser = Factory.Create(args);
            }
            catch (Exception ex)
            {
                Console.Write(GetHelp(parser));
                log.Error("Could not continue: " + ex.Message);
                Exit(1);
            }

            try
            {
                migrator = parser.Parse(args, new Migrator());
            }
            catch (Exception ex)
            {
                Console.Write(GetHelp(parser));
                log.Error("Error: " + ex.Message);
                Exit(1);
            }

            if (migrator != null)
            {
                migrator.Run();
            }

            Exit(Environment.ExitCode);
        }
Exemplo n.º 27
0
        private async Task StopApplication()
        {
            try
            {
                // NOTE: Service still can recieve and process requests here, so take care about it if you add logic here.

                await ApplicationContainer.Resolve <IShutdownManager>().StopAsync();
            }
            catch (Exception ex)
            {
                Log?.Error(nameof(StopApplication), ex);

                throw;
            }
        }
Exemplo n.º 28
0
        public void Connect(string hostname, int port)
        {
            Port = port;
            Host = hostname;

            try
            {
                _tcpClient = new System.Net.Sockets.TcpClient(Host, Port);
            }
            catch (SocketException ex)
            {
                Log?.Error("Connect failed", ex);
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 29
0
 internal static bool CopyFile(string file, string destinationFolder, Log log)
 {
     try
     {
         var sourceFileName = Path.GetFileName(file);
         if (sourceFileName == null || !File.Exists(file))
         {
             log.Error("File not found {0}", file);
             return false;
         }
         var destinationFilePath = Path.Combine(destinationFolder, sourceFileName);
         if (File.Exists(destinationFilePath))
         {
             File.Delete(destinationFilePath);
         }
         File.Copy(file, destinationFilePath);
     }
     catch (Exception e)
     {
         log.Error(e.Message);
         return false;
     }
     return true;
 }
Exemplo n.º 30
0
 public Login()
 {
     using (Log log = new Log("Glx.App.Login::Login()"))
     {
         try
         {
             DBWrapper.InitializeDB("\\database\\GlxDB.mdf", true);
             InitializeComponent();
         }
         catch (Exception ex)
         {
             log.Error(ex);
         }
     }
 }
Exemplo n.º 31
0
 /// <summary>
 /// Constructor : creates string array from entered string
 /// Working: Converts "Column1,Column2,Column3" to string[3]
 /// </summary>
 /// <param name="Columns_i"></param>
 public Table( string Columns_i )
 {
     using (Log log = new Log("Glx.DB.Table::Table()"))
     {
         try
         {
             sColumns = Columns_i;
             Columns = Strings.Split(Columns_i, ",", -1, CompareMethod.Text);
             nColumnCount = Columns.Length;
         }
         catch (Exception ex)
         {
             log.Error(ex);
         }
     }
 }
Exemplo n.º 32
0
        private async Task StartApplication()
        {
            try
            {
                // NOTE: Service not yet recieve and process requests here

                await ApplicationContainer.Resolve <IStartupManager>().StartAsync();

                HealthNotifier.Notify($"Env: {Program.EnvInfo} started");
            }
            catch (Exception ex)
            {
                Log?.Error(nameof(StartApplication), ex);

                throw;
            }
        }
Exemplo n.º 33
0
        public ServerChannel(ServerChannelConfiguration configuration)
        {
            Log?.Verbose(className, className, "Constructor fired");
            timer          = new Timer();
            timer.Interval = timerIntervalInSeconds * 1000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
            //ClientChannelManager = new ClientChannelManager();

            if (configuration == null)
            {
                Log?.Error(className, className, "No configuration found");
                Log?.Error(className, className, "Unable to to create proper Router Channel");
                return;
            }

            this.configuration = configuration;
        }
Exemplo n.º 34
0
        public T GetProperty <T>(string name, Log log, T def, Func <string, T> convert)
        {
            var str = GetString(name, log);

            try
            {
                if (!string.IsNullOrEmpty(str))
                {
                    return(convert(GetString(name, log)));
                }
            }
            catch (Exception e)
            {
                log?.Error(GetSource(name), null, "Failed to parse $(" + name + "): " + e.Message);
            }

            return(def);
        }
Exemplo n.º 35
0
        /// <summary>服务管理线程封装</summary>
        /// <param name="data"></param>
        protected virtual void ManagerThreadWaper(Object data)
        {
            // 暂停一会,等待各个任务线程完全启动
            Thread.Sleep(2 * 1000);
            while (true)
            {
                try
                {
                    CheckActive();

                    // 如果某一项检查需要重启服务,则返回true,这里跳出循环,等待服务重启
                    if (CheckMemory())
                    {
                        break;
                    }
                    if (CheckThread())
                    {
                        break;
                    }
                    if (CheckHandle())
                    {
                        break;
                    }
                    if (CheckAutoRestart())
                    {
                        break;
                    }

                    // 检查看门狗
                    CheckWatchDog();

                    Thread.Sleep(10 * 1000);
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    //WriteLine(ex.ToString());
                    Log?.Error(ex.GetTrue()?.ToString());
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Returns the index of a column by the statement: TableObject/"column_name"
        /// </summary>
        /// <param name="t"></param>
        /// <param name="sColumn"></param>
        /// <returns></returns>
        public static int operator /( Table t, string sColumn )
        {
            using (Log log = new Log("Glx.DB.Table::/()"))
            {
                try
                {
                    for (int nIndex = 0; nIndex < t.nColumnCount; nIndex++)
                        if (String.Compare(sColumn, t.Columns[nIndex], true) == 0)
                            return nIndex;
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    return -1;
                }
            }

            return -1;
        }
Exemplo n.º 37
0
        private async Task <bool> ExecuteJobAndContinue()
        {
            Log?.Info($"Start job \"{Name}\".");

            try
            {
                await _jobInstance.Execute();
            }
            catch (Exception ex)
            {
                if (StopOnError)
                {
                    Log?.Error($"Job \"{Name}\" could not be executed, throwing an exception and stopped.", ex);
                    return(false);
                }
                Log?.Error($"Job \"{Name}\" could not be executed, throwing an exception.", ex);
            }
            return(true);
        }
Exemplo n.º 38
0
        /// <summary>停止服务管理线程</summary>
        public void StopManagerThread()
        {
            var mt = ManagerThread;

            if (mt == null)
            {
                return;
            }
            if (mt.IsAlive)
            {
                try
                {
                    mt.Abort();
                }
                catch (Exception ex)
                {
                    //WriteLine(ex.ToString());
                    Log?.Error(ex.GetTrue()?.ToString());
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Load a dll file( AddIn file ) and get a user control named 'Icon' for Executing the AddIn
        /// </summary>
        /// <param name="sDllFileName"></param>
        /// <param name="sUserControlName"></param>
        /// <returns></returns>
        public static UserControl GetAddInIconFromDll(string sDllFileName)
        {
            using (Log log = new Log("Glx.Common.::GetAddInIconFromDll()"))
            {
                try
                {
                    Assembly assembly = Assembly.LoadFile(@sDllFileName);
                    object obj;
                    Type myType = assembly.GetType("Glx.AddIn.Icon");
                    obj = Activator.CreateInstance(myType);

                    UserControl userControl = (UserControl)obj;
                    return userControl;
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    return null;
                }
            }
        }
Exemplo n.º 40
0
        public bool SendEmail(Email email)
        {
            string methoName = MethodBase.GetCurrentMethod().Name;
            bool   isSent    = false;

            try
            {
                using (MailMessage mail = new MailMessage())
                {
                    mail.Subject    = email.Subject;
                    mail.Body       = email.Body;
                    mail.From       = new MailAddress(email.FromEmail, email.FromName);
                    mail.IsBodyHtml = email.IsHtml;
                    if (email.To == null)
                    {
                        email.To = new List <string>
                        {
                            email.FromEmail
                        };
                    }

                    if (email.To.Count == 0)
                    {
                        email.To.Add(email.FromEmail);
                    }
                    AddToEmailTo(mail, email.To);
                    AddToEmailCC(mail, email.CC);
                    AddToEmailBcc(mail, email.BCC);
                    smtp.Send(mail);
                    isSent = true;
                }
            }
            catch (Exception ex)
            {
                Log?.Error(className, methoName, ex.ToString());
                isSent = false;
            }

            return(isSent);
        }
Exemplo n.º 41
0
        public async Task StopAsync()
        {
            string methodName = MethodBase.GetCurrentMethod().Name;

            try
            {
                DisconnectAllClientChannels();
                if (boundChannel != null)
                {
                    await boundChannel.CloseAsync();

                    await boundChannel.DisconnectAsync();

                    await boundChannel.DeregisterAsync();


                    if (!boundChannel.Open)
                    {
                        if (!boundChannel.Registered)
                        {
                            boundChannel = null;
                        }
                    }
                }


                if (bossGroup != null)
                {
                    await Task.WhenAll(bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
                }
                if (workerGroup != null)
                {
                    await Task.WhenAll(workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
                }
            }
            catch (Exception ex)
            {
                Log?.Error(className, methodName, ex.ToString());
            }
        }
Exemplo n.º 42
0
        internal static uint parseSignedNumber(string val, int maxBitSize, int paramNo, Log log)
        {
            Match m = Regex.Match(val, @"^(?i:" +
                @"(?:0(?<1>x)(?<2>[0-9a-f]+))|" + // hex values 0x12AB
                @"(?:0(?<1>o)(?<2>[0-7]+))|" + // oct values 0o7564
                @"(?:0(?<1>b)(?<2>[01]+))|" + // bin values 0b1101010
                @"(?<2>-?(?<1>\d)\d*(?:E[+-]?\d+)?)" +//simple number with optional exponent(nnnExx, nnnE+xx, and nnnE-xx)
                //@"|(?:(?<1>@)(?<2>[a-z_][0-9a-z_]+))" + //labels  @myLabel (removed: labels processed before parsing)
                @")$");

            if (!m.Groups[2].Success)
            {
                log.Error("param {0}: unable to recognize constant '{1}'", paramNo, val);
                return 0;
            }

            char opType = m.Groups[1].Value[0];
            string opVal = m.Groups[2].Value;

            if (opVal == "")
                log.Error("param {0}: compiler error 4360 '{1}'", paramNo, val);

            int num;
            if (opType > '0' && opType <= '9')
                num = Int32.Parse(opVal, NumberStyles.AllowLeadingSign | NumberStyles.AllowExponent);
            else // if (opType == 'x' || opType == 'o' || opType == 'b')
                num = Convert.ToInt32(opVal, (opType == 'x') ? 16 : (opType == 'o') ? 8 : 2);

            if (num > ((1 << maxBitSize - 1) - 1))
                log.Error("param {0}: The value '{1}' will not fit in {2} bits", paramNo, val, maxBitSize);

            if (num < -(1 << maxBitSize))
                log.Error("param {0}: The value '{1}' will not fit in {2} bits", paramNo, val, maxBitSize);

            int mask = ((1 << maxBitSize) - 1);

            return (uint)(num & mask); //returned as uint for b32
        }
Exemplo n.º 43
0
 public static void Main(string[] args)
 {
     if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/settings.json"))
     {
         Configuration config = Configuration.LoadConfiguration(AppDomain.CurrentDomain.BaseDirectory + "/settings.json");
         Log mainLog = new Log(config.MainLog, null);
         foreach (Configuration.BotInfo info in config.Bots)
         {
             mainLog.Info("Launching Bot " + info.DisplayName + "...");
             new Thread(() =>
             {
                 int crashes = 0;
                 while (crashes < 1000)
                 {
                     try
                     {
                         new Bot(info, config.ApiKey, (Bot bot, SteamID sid) =>
                         {
                             return (SteamBot.UserHandler)System.Activator.CreateInstance(Type.GetType(info.BotControlClass), new object[] { bot, sid });
                         });
                     }
                     catch (Exception e)
                     {
                         mainLog.Error("Error With Bot: " + e);
                         crashes++;
                     }
                 }
             }).Start();
             Thread.Sleep(5000);
         }
         MySQL.start();
     }
     else
     {
         Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
         Console.WriteLine("Configuration File Does not exist. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
     }
 }
Exemplo n.º 44
0
 public static void Main(string[] args)
 {
     if (System.IO.File.Exists("settings.json"))
     {
         Configuration config = Configuration.LoadConfiguration("settings.json");
         Log mainLog = new Log(config.MainLog, null);
         foreach (Configuration.BotInfo info in config.Bots)
         {
             mainLog.Info("Launching Bot " + info.DisplayName + "...");
             new Thread(() =>
             {
                 int crashes = 0;
                 while (crashes < 1000)
                 {
                     try
                     {
                         new Bot(info, config.ApiKey, (Bot bot, SteamID sid) =>
                         {
                             return new SimpleUserHandler(bot, sid);
                         }, true);
                     }
                     catch (Exception e)
                     {
                         mainLog.Error("Error With Bot: " + e);
                         crashes++;
                     }
                 }
             }).Start();
             Thread.Sleep(5000);
         }
     }
     else
     {
         Console.WriteLine("Configuration File Does not exist. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
     }
 }
Exemplo n.º 45
0
        public static void ExitApplication(Application application, Log log)
        {
            const string prefix = "Application - Exit";
            if (application != null)
            {
                log.Info(prefix, "Closing application.");
                try
                {
                    application.Close();
                    if (application.Process.HasExited)
                    {
                        return;
                    }

                    application.Process.WaitForExit(Constants.ShutdownWaitTimeInMilliSeconds());
                    if (!application.Process.HasExited)
                    {
                        application.Kill();
                    }
                }
                catch (InvalidOperationException)
                {
                    // Do nothing because the cause for this exception is when there is no process
                    // associated with the application.Process object.
                }
                catch (Exception e)
                {
                    log.Error(
                        prefix,
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Error trying to terminate application. Error was: {0}",
                            e));
                }
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Insert data into table
        /// e.g. DDL.InsertInto("Sample", "col1,col2", "10,20");
        /// </summary>
        /// <param name="sTableName"></param>
        /// <param name="sColumns_i"></param>
        /// <param name="sValues_i"></param>
        public static void InsertInto(string sTableName, string sColumns_i, string sValues_i )
        {
            using( Log log = new Log( "Glx.DB.DDL.InsertInto()" ) )
            {
                try
                {
                    string sQuerry = "INSERT INTO " + sTableName + "(";
                    string[] sColums = Strings.Split(sColumns_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sColums[0];

                    for (int nIndex = 1; nIndex < sColums.Length; nIndex++)
                        sQuerry = sQuerry + "," + sColums[nIndex];

                    sQuerry += ") VALUES(";

                    string[] sValues = Strings.Split(sValues_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sValues[0];

                    for (int nIndex = 1; nIndex < sValues.Length; nIndex++)
                        sQuerry = sQuerry + "," + sValues[nIndex];

                    sQuerry += ")";

                    log.PutQuerry( sQuerry);
                    DBWrapper.ExecuteNonQueryEx(sQuerry);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// SOPK encoding format 
        /// |ENCODING(4)-28|OP(5)-23|SDST(7)-16|SIMM16(int,16)-0|
        /// </summary>
        private static OpCode encodeSOPK(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // SIMM16	0	15	int	    16	
            // SDST	    16	22	enum	7	Scalar destination for instruction. Same codes as for SIMM16, above, except that this can use only codes 0 to 127. 16-bit integer input for opcode. Signedness is determined by opcode. 
            // OP	    23	27	enum	5	Opcode.
            // ENCODING	28	31	enum	4	Must be 1 0 1 1.
            OpCode op_code = new OpCode { code = instr.opCode };

            string[] args = Regex.Split(options, @"\s*[,\s]\s*");

            if (args.Length < instr.opCtMin)
            {
                log.Error("{0} should have at least {1} argument(s).", instr.name, instr.opCtMin);
                return op_code;
            }
            else if (args.Length > instr.opCtMax)
            {
                log.Error("{0} should have no more then {1} argument(s).", instr.name, instr.opCtMax);
                return op_code;
            }

            uint immd = ParseOperand.parseSignedNumber(args[0], 16, 2, log);

            uint sdst = ParseOperand.parseOperand(args[1], OpType.SCALAR_DST, 1, log).reg;

            op_code.code |= (sdst << 16) | immd;

            return op_code;
        }
Exemplo n.º 48
0
        /// <summary>
        /// Primary entry point to setup a new algorithm
        /// </summary>
        /// <param name="algorithm">Algorithm instance</param>
        /// <param name="brokerage">New brokerage output instance</param>
        /// <param name="job">Algorithm job task</param>
        /// <param name="resultHandler">The configured result handler</param>
        /// <param name="transactionHandler">The configurated transaction handler</param>
        /// <param name="realTimeHandler">The configured real time handler</param>
        /// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
        public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket job, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
        {
            _algorithm = algorithm;

            // verify we were given the correct job packet type
            var liveJob = job as LiveNodePacket;

            if (liveJob == null)
            {
                AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
                return(false);
            }

            // verify the brokerage was specified
            if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
            {
                AddInitializationError("A brokerage must be specified");
                return(false);
            }


            // attach to the message event to relay brokerage specific initialization messages
            EventHandler <BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
            {
                if (args.Type == BrokerageMessageType.Error)
                {
                    AddInitializationError(string.Format("Brokerage Error Code: {0} - {1}", args.Code, args.Message));
                }
            };

            try
            {
                Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");

                resultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm...");

                //Execute the initialize code:
                var controls           = job.Controls;
                var isolator           = new Isolator();
                var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(300), () =>
                {
                    try
                    {
                        //Set the default brokerage model before initialize
                        algorithm.SetBrokerageModel(_factory.BrokerageModel);
                        //Set our parameters
                        algorithm.SetParameters(job.Parameters);
                        //Algorithm is live, not backtesting:
                        algorithm.SetLiveMode(true);
                        //Initialize the algorithm's starting date
                        algorithm.SetDateTime(DateTime.UtcNow);
                        //Set the source impl for the event scheduling
                        algorithm.Schedule.SetEventSchedule(realTimeHandler);
                        //Initialise the algorithm, get the required data:
                        algorithm.Initialize();
                        if (liveJob.Brokerage != "PaperBrokerage")
                        {
                            //Zero the CashBook - we'll populate directly from brokerage
                            foreach (var kvp in algorithm.Portfolio.CashBook)
                            {
                                kvp.Value.SetAmount(0);
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        AddInitializationError(err.Message);
                    }
                });

                if (!initializeComplete)
                {
                    AddInitializationError("Initialization timed out.");
                    return(false);
                }

                // let the world know what we're doing since logging in can take a minute
                resultHandler.SendStatusUpdate(AlgorithmStatus.LoggingIn, "Logging into brokerage...");

                brokerage.Message += brokerageOnMessage;

                algorithm.Transactions.SetOrderProcessor(transactionHandler);
                algorithm.PostInitialize();

                Log.Trace("BrokerageSetupHandler.Setup(): Connecting to brokerage...");
                try
                {
                    // this can fail for various reasons, such as already being logged in somewhere else
                    brokerage.Connect();
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    AddInitializationError(string.Format("Error connecting to brokerage: {0}. " +
                                                         "This may be caused by incorrect login credentials or an unsupported account type.", err.Message));
                    return(false);
                }

                if (!brokerage.IsConnected)
                {
                    // if we're reporting that we're not connected, bail
                    AddInitializationError("Unable to connect to brokerage.");
                    return(false);
                }

                Log.Trace("BrokerageSetupHandler.Setup(): Fetching cash balance from brokerage...");
                try
                {
                    // set the algorithm's cash balance for each currency
                    var cashBalance = brokerage.GetCashBalance();
                    foreach (var cash in cashBalance)
                    {
                        Log.Trace("BrokerageSetupHandler.Setup(): Setting " + cash.Symbol + " cash to " + cash.Amount);
                        algorithm.Portfolio.SetCash(cash.Symbol, cash.Amount, cash.ConversionRate);
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    AddInitializationError("Error getting cash balance from brokerage: " + err.Message);
                    return(false);
                }

                Log.Trace("BrokerageSetupHandler.Setup(): Fetching open orders from brokerage...");
                try
                {
                    // populate the algorithm with the account's outstanding orders
                    var openOrders = brokerage.GetOpenOrders();
                    foreach (var order in openOrders)
                    {
                        // be sure to assign order IDs such that we increment from the SecurityTransactionManager to avoid ID collisions
                        Log.Trace("BrokerageSetupHandler.Setup(): Has open order: " + order.Symbol.ToString() + " - " + order.Quantity);
                        order.Id = algorithm.Transactions.GetIncrementOrderId();
                        transactionHandler.Orders.AddOrUpdate(order.Id, order, (i, o) => order);
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    AddInitializationError("Error getting open orders from brokerage: " + err.Message);
                    return(false);
                }

                Log.Trace("BrokerageSetupHandler.Setup(): Fetching holdings from brokerage...");
                try
                {
                    // populate the algorithm with the account's current holdings
                    var holdings = brokerage.GetAccountHoldings();
                    var supportedSecurityTypes = new HashSet <SecurityType> {
                        SecurityType.Equity, SecurityType.Forex, SecurityType.Cfd
                    };
                    var minResolution = new Lazy <Resolution>(() => algorithm.Securities.Select(x => x.Value.Resolution).DefaultIfEmpty(Resolution.Second).Min());
                    foreach (var holding in holdings)
                    {
                        Log.Trace("BrokerageSetupHandler.Setup(): Has existing holding: " + holding);

                        // verify existing holding security type
                        if (!supportedSecurityTypes.Contains(holding.Type))
                        {
                            Log.Error("BrokerageSetupHandler.Setup(): Unsupported security type: " + holding.Type + "-" + holding.Symbol.Value);
                            AddInitializationError("Found unsupported security type in existing brokerage holdings: " + holding.Type + ". " +
                                                   "QuantConnect currently supports the following security types: " + string.Join(",", supportedSecurityTypes));

                            // keep aggregating these errors
                            continue;
                        }

                        if (!algorithm.Portfolio.ContainsKey(holding.Symbol))
                        {
                            Log.Trace("BrokerageSetupHandler.Setup(): Adding unrequested security: " + holding.Symbol.ToString());
                            // for items not directly requested set leverage to 1 and at the min resolution
                            algorithm.AddSecurity(holding.Type, holding.Symbol.Value, minResolution.Value, null, true, 1.0m, false);
                        }
                        algorithm.Portfolio[holding.Symbol].SetHoldings(holding.AveragePrice, (int)holding.Quantity);
                        algorithm.Securities[holding.Symbol].SetMarketPrice(new TradeBar
                        {
                            Time     = DateTime.Now,
                            Open     = holding.MarketPrice,
                            High     = holding.MarketPrice,
                            Low      = holding.MarketPrice,
                            Close    = holding.MarketPrice,
                            Volume   = 0,
                            Symbol   = holding.Symbol,
                            DataType = MarketDataType.TradeBar
                        });
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    AddInitializationError("Error getting account holdings from brokerage: " + err.Message);
                    return(false);
                }

                //Set the starting portfolio value for the strategy to calculate performance:
                StartingPortfolioValue = algorithm.Portfolio.TotalPortfolioValue;
                StartingDate           = DateTime.Now;
            }
            catch (Exception err)
            {
                AddInitializationError(err.Message);
            }
            finally
            {
                if (brokerage != null)
                {
                    brokerage.Message -= brokerageOnMessage;
                }
            }

            return(Errors.Count == 0);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Retrieves the templates
        /// </summary>
        public async Task <List <TemplateViewModel> > GetTemplates()
        {
            try
            {
                using (var context = new WebAppContext())
                {
                    var email      = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value;
                    var userGroups = ClaimsPrincipal.Current.FindAll("groups").Select(g => g.Value).ToList();
                    var adminUser  = UserRoleHelper.AdminUserName;

                    var graphGroups = await new GraphGroupController().GetGraphGroups();
                    var graphUsers  = await new GraphUserController().GetGetGraphUsers();
                    graphGroups.AddRange(graphUsers.Select(user => new GraphGroupsViewModel()
                    {
                        ObjectId    = user.UserPrincipalName,
                        DisplayName = user.DisplayName
                    }));

                    var intersectGroups = (from gGroup in graphGroups from uGroup in userGroups where gGroup.ObjectId == uGroup select gGroup).ToList();
                    intersectGroups.Add(new GraphGroupsViewModel()
                    {
                        ObjectId = email, DisplayName = email
                    });
                    intersectGroups.Add(new GraphGroupsViewModel()
                    {
                        ObjectId = "*", DisplayName = "Available to All"
                    });
                    graphGroups.Add(new GraphGroupsViewModel()
                    {
                        ObjectId = email, DisplayName = email
                    });
                    graphGroups.Add(new GraphGroupsViewModel()
                    {
                        ObjectId = "*", DisplayName = "Available to All"
                    });

                    var templates = await context.TemplateJsons.ToListAsync();

                    var result = new List <TemplateViewModel>();
                    if (email == adminUser)
                    {
                        foreach (var template in templates)
                        {
                            var uGroups = template.TemplateUsersGroup.Split(',');
                            template.TemplateUsersGroup = GetInlineGroups(uGroups, graphGroups);

                            result.Add(template);
                        }
                    }
                    else
                    {
                        foreach (var template in templates)
                        {
                            var uGroups         = template.TemplateUsersGroup.Split(',');
                            var intersectResult = GetInlineGroups(uGroups, intersectGroups);
                            if (intersectResult.Length > 0)
                            {
                                var groups = GetInlineGroups(uGroups, graphGroups);
                                template.TemplateUsersGroup = groups;
                                result.Add(template);
                            }
                        }
                    }

                    return(result);
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
                return(new List <TemplateViewModel>());
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// DS encoding format 
        /// |ENCODE(6)-26|--OP(8)-18--|GDS(1)-17|reserved(1)-16|OFFSET1(8)-8|OFFSET0(8)-0|
        /// |VDST(8)-56|DATA1(8)-48|DATA0(8)-40|ADDR(8)-32|
        /// </summary>
        private static OpCode encodeDS(InstInfo instr, string options, Log log)
        {
	        string[] args = Regex.Split(options, @"\s*[,\s]\s*");
	        
            OpCode op_code = new OpCode{code = instr.opCode};

            if (instr.name == "ds_nop")
            {
                if (args.Length > 1 || args[0] != "")
                    log.Warning("ds_nop does not support any options");
                op_code.code = instr.opCode;
                op_code.literal = 0;
                return op_code;
            }
            if (args.Length < 4)
            {
                log.Error("number of passed operands is too low");
                return op_code;
            }

            // Setup arguments
            
            string vdst_str	= args[0];
	        string addr_str	= args[1];
	        string data0_str= args[2];
	        string data1_str= args[3];
	       



	        // Parse optional parameters
	        for (int i = 4; i < args.Length; i++)
	        {
		        if (args[i]== "gds")
			        op_code.code |= (1 << 17);
		        else if (args[i].StartsWith("offset"))
		        {
                    Match m = Regex.Match(args[i], @"offset(0|1):([0-9a-fxo]+)$");
                    uint val = 0;
                    if (m.Success)
                        val = ParseOperand.parseUnSignedNumber(m.Groups[2].Value, 16, i, log); //hack: sometimes this is 8 bits(not 16)
                    else
                        log.Error("incorrect offset format - example OFFSET0:123");

                    op_code.code |= val << (m.Groups[1].Value == "0" ? 0 : 8);
		        }
	        }

            uint vdst_val = ParseOperand.parseOnlyVGPR(vdst_str, 1, log);
            uint addr_op = ParseOperand.parseOnlyVGPR(addr_str, 2, log);
            uint data0_op = ParseOperand.parseOnlyVGPR(data0_str, 3, log);
            uint data1_op = ParseOperand.parseOnlyVGPR(data1_str, 4, log);

            op_code.literal = addr_op | data0_op << 8 | data1_op << 16 | vdst_val << 24;

            return op_code;
        }
Exemplo n.º 51
0
        private static uint processOModFromRegEx(Match m, Log log)
        {
            uint val = 0;
            if (m.Groups["omod"].Success)
            {
                if (!m.Groups["omod"].Value.Contains("."))
                    log.Warning("omod or mul arguments should use a period(.) in the number to show it is float");

                if (Regex.Match(m.Groups["omod"].Value, "^4.?0*$").Success)
                    val |= 1 << 58;
                else if (Regex.Match(m.Groups["omod"].Value, "^2.?0*$").Success)
                    val |= 2 << 58;
                else if (Regex.Match(m.Groups["omod"].Value, "^0?.50*$").Success)
                    val |= 3 << 58;
                else
                    log.Error("unknown omod format, valid examples: omod:2.0, omod:4.0, omod:0.5 "
                        +"mul(2.0) mul(4.0) mul(0.5) or mul=2.0 mul=4.0 mul=0.5");
            }
            return val;
        }
Exemplo n.º 52
0
        /// <summary>
        /// VOP1 encoding format 
        /// |ENCODE(7)-25|VDST(8)-17|OP(8)-9|SRC0(9)-0|
        /// </summary>
        private static OpCode encodeVOP1(InstInfo instr, string options, Log log)
        {
            OpCode op_code = new OpCode { code = instr.opCode };

            string[] args = Regex.Split(options, @"\s*[,\s]\s*");

            if (args.Length < instr.opCtMin)
            {
                log.Error("{0} should have at least {1} argument(s).", instr.name, instr.opCtMin);
                return op_code;
            }
            if (args.Length > instr.opCtMax)
            {
                log.Error("{0} should have no more then {1} argument(s).", instr.name, instr.opCtMax);
                return op_code;
            }

            uint vdst;
            OpInfo vsrc0;
            if (instr.name == "v_readfirstlane_b32")
            {
                vdst = ParseOperand.parseOnlySGPR(args[0], 1, log);
                vsrc0 = ParseOperand.parseOperand(args[1], OpType.VGPR | OpType.LDS_DIRECT, 2, log);
            }
            else
            {
                vdst = ParseOperand.parseOnlyVGPR(args[0], 1, log);
                vsrc0 = ParseOperand.parseOperand(args[1], OpType.ALL, 2, log);
                if (vsrc0.flags.HasFlag(OpType.LITERAL))
                    op_code.literal = vsrc0.value;
            }

            op_code.code |= (vdst << 17) | vsrc0.reg;

            return op_code;
        }
Exemplo n.º 53
0
        /// <summary>
        /// VOP2 encoding format 
        /// |Encode(1)-31|OP(6)-25|VDST(8)-17|VSRC1(8)-9|SRC0(9)-0|
        /// </summary>
        private static OpCode encodeVOP2(InstInfo instr, string options, Log log)
        {
            OpCode op_code = new OpCode { code = instr.opCode };

            string[] args = Regex.Split(options, @"\s*[,\s]\s*");
            int argCt = args.Length;

            if (argCt < 3)
            {
                log.Error("{0} should have at least {1} argument(s).", instr.name, instr.opCtMin);
                return op_code;
            }

            // handle "vcc" destination in VOP2.  example: v_add_a32 v0, vcc, v1, v2
            if (instr.OpNum.IsBetween<uint>(36, 43))
                if (args[1] == "vcc")
                {
                    for (int i = 2; i < args.Length; i++)
                        args[i - 1] = args[i];
                    argCt--;
                }
                else
                    log.Warning("{0} should specify VCC as output param for clarity.", instr.name);

            if (argCt > instr.opCtMax)
            {
                log.Error("{0} should have no more then {1} argument(s).", instr.name, instr.opCtMax);
                return op_code;
            }

            uint vdst, vsrc1;
            OpInfo vsrc0;
            if (instr.name == "v_readlane_b32")
            {
                vdst = ParseOperand.parseOnlySGPR(args[0], 1, log, OpType.SCALAR_DST);
                vsrc0 = ParseOperand.parseOperand(args[1], OpType.VGPR | OpType.LDS_DIRECT | OpType.M0, 2, log);
                vsrc1 = ParseOperand.parseOperand(args[2], OpType.SGPR | OpType.LDS_DIRECT | OpType.M0 | OpType.INLINE, 3, log).reg;
            }
            else if (instr.name == "v_writelane_b32")
            {
                vdst = ParseOperand.parseOnlyVGPR(args[0], 1, log);
                vsrc0 = ParseOperand.parseOperand(args[1], OpType.SGPR | OpType.M0 | OpType.EXEC | OpType.CONST, 2, log);
                vsrc1 = ParseOperand.parseOperand(args[2], OpType.SGPR | OpType.M0 | OpType.INLINE, 3, log).reg;
            }
            else
            {
                vdst = ParseOperand.parseOnlyVGPR(args[0], 1, log);
                vsrc0 = ParseOperand.parseOperand(args[1], OpType.ALL, 2, log);
                if (vsrc0.flags.HasFlag(OpType.LITERAL))
                    op_code.literal = vsrc0.value;
                vsrc1 = ParseOperand.parseOnlyVGPR(args[2], 2, log);
            }

            op_code.code |= (vdst << 17) | (vsrc1 << 9) | vsrc0.reg;

            return op_code;
        }
Exemplo n.º 54
0
        /// <summary>
        /// SOPP encoding format 
        /// |ENCODING(9)-23|OP(7)-16|SIMM16(int,16)-0|
        /// </summary>
        private static OpCode encodeSOPP(InstInfo instr, string options, Log log)
        {
            if (instr.name == "s_waitcnt")
            {    
                uint VMCt= 0x0F/*0-15*/, LGKMCt= 0x0F/*0-15*/, EXPCt= 0x07/*0-7*/;

                //string regex = @"(?:(?:"+ 
                //@"vm_?(?:ct|cnt|count)=?\(?(?<vm>\d+)\)?|"+ //vmcnt(#),vm_ct(#), vm_count(#) vmcount(#)...
                //@"lgkm_?(?:ct|cnt|count)=?\((?<lgkm>\d+)\)|" + //vmcnt=#,vm_ct=#, vm_count=# vmcount=#...
                //@"exp_?(?:ct|cnt|count)=?\((?<exp>\d+)\)|" +
                //@")\s*,?\s*)+";

                MatchCollection matches = Regex.Matches(options, @"(vm|lgkm|exp)_?(?:ct|cnt|count)=?\(?(\d+)\)?");

                foreach (Match m in matches)
                {
                    string type = m.Groups[1].Value;
                    uint val = uint.Parse(m.Groups[2].Value);
                    switch (type)
                    {
                        case "lgkm":
                            LGKMCt = val;
                            if (LGKMCt > 31)
                                log.Warning("LGKM_CNT must be between 0 and 15.");
                            break;
                        case "vm":
                            VMCt = val;
                            if (VMCt > 15)
                                log.Warning("VM_CNT must be between 0 and 15.");
                            break;
                        case "exp":
                            EXPCt = val;
                            if (EXPCt > 7)
                                log.Warning("EXPCt must be between 0 and 7.");
                            break;
                    }
                }

                return new OpCode { code = instr.opCode | VMCt | (LGKMCt<<8) | (EXPCt<<4) };
            }

            uint immd = 0; // can be signed or un-signed
            if (options == "")
            {
                if (instr.opCtMin > 0)
                {
                    log.Error("{0} expected argument(s).", instr.name);
                    return (new OpCode { code = instr.opCode });
                }
            }
            else
            {
                string[] args = Regex.Split(options, @"\s*[,\s]\s*");

                if (args.Length != instr.opCtMax)
                {
                    log.Error("{0} should have {1} argument(s).", instr.name, instr.opCtMax, instr.opCtMax);
                    return (new OpCode { code = instr.opCode});
                }

                immd = ParseOperand.parseSignedNumber(args[0], 16, 1, log);
            }

            if ((immd & 0xffff0000) != 0)
               log.Error("The immediate value seems to use more then 16 bits.");

            return new OpCode { code = instr.opCode | immd };
        }
Exemplo n.º 55
0
        /// <summary>
        /// VINTRP encoding format 
        /// ENCODING(6)-26|VDST(8)-18|OP(2)-16|ATTR(6)-10|ATTRCHAN(2)-8|VSRC(8)-0|
        /// </summary>
        private static OpCode encodeVINTRP(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // VSRC	    0	7	enum	8	Vector General-Purpose Registers (VGPR) containing the i/j coordinate by which to multiply one of the parameter components.
            // ATTRCHAN	8	9	enum	2	Attribute component to interpolate. See Section 10.1 on page 10-1.
            // ATTR	    10	15	int	    6	Attribute to interpolate.
            // OP	    16	17	enum	2	0:V_INTERP_P1_F32: D = P10 * S + P0; parameter interpolation. 1:V_INTERP_P2_F32: D = P20 * S + D; parameter interpolation. 2: V_INTERP_MOV_F32: D = {P10,P20,P0}[S]; parameter load. 3: reserved.
            // VDST	    18	25	enum	8	Vector General-Purpose Registers (VGPR 0-255) to which results are written, and, optionally, from which they are read when accumulating results.
            // ENCODING	26	31	enum	6	Must be 1 1 0 0 1 0.

            string attrchanString = "0";
            uint vdst = 0, vsrc = 0, attr = 0, attrchan = 0;

            if (instr.name == "v_interp_mov_f32")
            {
                Match m = Regex.Match(options, 
                    @"v(\d+)\s*[,\s]\s*(p?)(\d+)\s*[,\s]\s*" + // first two opps
                    @"(?:attr(\d+)\.([xyzw0123])|" + // for v_interp_mov_f32 v0, p0, attr0.z format
                    @"(?<5>\d+)\s*[,\s]\s*(?<4>\d+)\s*[,\s]\s*\[\s*m0\s*\])"); // for v_interp_mov_f32 v0, p0, 3, 0, [m0] format 

                if (!m.Success)
                    log.Error("v_interp_mov_f32 should be in the format 'v1, p20, attr0.x' or 'v1, p20, 0, 0, [m0]'.");
                else
                {
                    vdst = uint.Parse(m.Groups[1].Value);
                    vsrc = uint.Parse(m.Groups[3].Value);
                    attr = uint.Parse(m.Groups[4].Value);
                    attrchanString = m.Groups[5].Value;
                    
                    if (m.Groups[2].Value == "p")
                    {
                        if (vsrc == 10) vsrc = 0;
                        else if (vsrc == 20) vsrc = 1;
                        else if (vsrc == 0) vsrc = 2;
                    }

                    if (vsrc > 2)
                        log.Error("v_interp_mov_f32 p should be p10,p20,p0 or 0,1,2)");
                }
            }
            else if (instr.name == "v_interp_p1_f32")
            {
                Match m = Regex.Match(options, 
                    @"v(\d+)\s*[,\s]\s*(v)(\d+)\s*[,\s]\s*" + // first two opps
                    @"(?:attr(\d+)\.([xyzw0123])|" + // for v_interp_p1_f32 v0, p0, attr0.z format
                    @"(?<5>\d+)\s*[,\s]\s*(?<4>\d+)\s*[,\s]\s*\[\s*m0\s*\])"); // for v_interp_p1_f32 v0, v0, 3, 0, [m0] format 
                
                if (!m.Success)
                    log.Error("v_interp_p1_f32 should be in the format 'v2, v4, attr0.x' or 'v2, v4, 0, 0, [m0]'.");
                else
                {
                    vdst = uint.Parse(m.Groups[1].Value);
                    vsrc = uint.Parse(m.Groups[3].Value);
                    attr = uint.Parse(m.Groups[4].Value);
                    attrchanString = m.Groups[5].Value;
                    
                    if (vsrc > 255)
                        log.Error("v_interp_p1_f32 vsrc should be less then 256.");
                }
            }
            else if (instr.name == "v_interp_p2_f32")
            {
                Match m = Regex.Match(options, 
                    @"v(\d+)\s*[,\s]\s*(?:\[v(\d+)\]\s*[,\s]\s*)?v(\d+)\s*[,\s]\s*" + // first two opps 
                    @"(?:attr(\d+)\.([xyzw0123])|" + // for v_interp_p2_f32 v0, p0, attr0.z format
                    @"(?<5>\d+)\s*[,\s]\s*(?<4>\d+)\s*[,\s]\s*\[\s*m0\s*\])"); // for v_interp_p2_f32 v0, v0, 3, 0, [m0] format 
                
                if (!m.Success)
                    log.Error("v_interp_p2_f32 should be in the format 'v2, [v2], v4, attr0.x' or 'v2, v4, 0, 0, [m0]'.");
                else
                {
                    vdst = uint.Parse(m.Groups[1].Value);
                    vsrc = uint.Parse(m.Groups[3].Value);
                    attr = uint.Parse(m.Groups[4].Value);
                    attrchanString = m.Groups[5].Value;

                    if (vsrc > 255)
                        log.Error("v_interp_p2_f32 vsrc should be less then 256.");
                }

                if (m.Groups[2].Success)
                    if (m.Groups[1].Value != m.Groups[2].Value)
                        log.Error("The first two vector register numbers do not match. (i.e. v_interp_p2_f32 v7 [v7]...");
            }

            if (attrchanString == "x") attrchan = 0;
            else if (attrchanString == "y") attrchan = 1;
            else if (attrchanString == "z") attrchan = 2;
            else if (attrchanString == "w") attrchan = 3;
            else attrchan = uint.Parse(attrchanString);

            if (vdst > 255)
            {
                log.Error("{0} vdst should be less then 256.", instr.name);
                vdst = 0;
            }
            if (attr > 31)
            {
                log.Error("{0} attr should be 0 to 31.", instr.name);
                attr = 0;
            }
            if (attrchan > 3)
            {
                log.Error("{0} attrchan should be x,y,z,w or 0,1,2,3)", instr.name);
                attrchan = 0;
            }
            return new OpCode { code = instr.opCode | (vdst << 18) | (attr << 10) | (attrchan << 8) | vsrc };
        }
Exemplo n.º 56
0
        public override async Task UpdateBalanceAsync(
            CancellationToken cancellationToken = default)
        {
            var fa2 = FA2;

            var txs = (await DataRepository
                       .GetTransactionsAsync(Currency, fa2.TransactionType)
                       .ConfigureAwait(false))
                      .Cast <TezosTransaction>()
                      .ToList();

            var internalTxs = txs.Aggregate(new List <TezosTransaction>(), (list, tx) =>
            {
                if (tx.InternalTxs != null)
                {
                    list.AddRange(tx.InternalTxs);
                }

                return(list);
            });

            // calculate balances
            var totalBalanceSum         = 0m;
            var totalUnconfirmedIncome  = 0m;
            var totalUnconfirmedOutcome = 0m;

            var addresses = new Dictionary <string, WalletAddress>();

            foreach (var tx in txs.Concat(internalTxs))
            {
                var selfAddresses = new HashSet <string>();

                var isFromSelf = await IsSelfAddressAsync(tx.From, cancellationToken)
                                 .ConfigureAwait(false);

                //if (tx.Type.HasFlag(BlockchainTransactionType.Output))
                if (isFromSelf)
                {
                    selfAddresses.Add(tx.From);
                }

                var isToSelf = await IsSelfAddressAsync(tx.To, cancellationToken)
                               .ConfigureAwait(false);

                //if (tx.Type.HasFlag(BlockchainTransactionType.Input))
                if (isToSelf)
                {
                    selfAddresses.Add(tx.To);
                }

                foreach (var address in selfAddresses)
                {
                    var isIncome    = address == tx.To;
                    var isOutcome   = address == tx.From;
                    var isConfirmed = tx.IsConfirmed;
                    var isFailed    = tx.State == BlockchainTransactionState.Failed;

                    var income = isIncome && !isFailed
                        ? tx.Amount.FromTokenDigits(fa2.DigitsMultiplier)
                        : 0;

                    var outcome = isOutcome && !isFailed
                        ? -tx.Amount.FromTokenDigits(fa2.DigitsMultiplier)
                        : 0;

                    if (addresses.TryGetValue(address, out var walletAddress))
                    {
                        walletAddress.Balance            += isConfirmed ? income + outcome : 0;
                        walletAddress.UnconfirmedIncome  += !isConfirmed ? income : 0;
                        walletAddress.UnconfirmedOutcome += !isConfirmed ? outcome : 0;
                    }
                    else
                    {
                        walletAddress = await DataRepository
                                        .GetWalletAddressAsync(Currency, address)
                                        .ConfigureAwait(false);

                        if (walletAddress == null)
                        {
                            continue;
                        }

                        walletAddress.Balance            = isConfirmed ? income + outcome : 0;
                        walletAddress.UnconfirmedIncome  = !isConfirmed ? income : 0;
                        walletAddress.UnconfirmedOutcome = !isConfirmed ? outcome : 0;
                        walletAddress.HasActivity        = true;

                        addresses.Add(address, walletAddress);
                    }

                    totalBalanceSum         += isConfirmed ? income + outcome : 0;
                    totalUnconfirmedIncome  += !isConfirmed ? income : 0;
                    totalUnconfirmedOutcome += !isConfirmed ? outcome : 0;
                }
            }

            Balance = totalBalanceSum;

            var totalBalance = 0m;

            foreach (var wa in addresses.Values)
            {
                var fa2Api = fa2.BlockchainApi as ITokenBlockchainApi;

                var balanceResult = await fa2Api
                                    .TryGetTokenBigMapBalanceAsync(
                    address : wa.Address,
                    pointer : fa2.TokenPointerBalance,
                    cancellationToken : cancellationToken)
                                    .ConfigureAwait(false);

                if (balanceResult.HasError)
                {
                    Log.Error("Error while getting token balance for {@address} with code {@code} and description {@description}",
                              wa.Address,
                              balanceResult.Error.Code,
                              balanceResult.Error.Description);

                    continue; // todo: may be return?
                }

                wa.Balance = balanceResult.Value.FromTokenDigits(fa2.DigitsMultiplier);

                totalBalance += wa.Balance;
            }

            if (totalBalanceSum != totalBalance)
            {
                Log.Warning("Transaction balance sum is different from the actual {@name} token balance",
                            fa2.Name);

                Balance = totalBalance;
            }

            // upsert addresses
            await DataRepository
            .UpsertAddressesAsync(addresses.Values)
            .ConfigureAwait(false);

            UnconfirmedIncome  = totalUnconfirmedIncome;
            UnconfirmedOutcome = totalUnconfirmedOutcome;

            RaiseBalanceUpdated(new CurrencyEventArgs(Currency));
        }
Exemplo n.º 57
0
        /// <summary>
        /// SOPC encoding format 
        /// |ENCODING(9)-23|OP(7)-16|SSRC1(8)-8|SSRC0(8)-0|
        /// </summary>
        private static OpCode encodeSOPC(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // SSRC0	0	7	enum	8	Source 0. First operand for the instruction.
            // SSRC1	8	15	enum	8	Source 1. Second operand for instruction. Same codes as for SSRC0, above.
            // OP	    16	22	enum	7	
            // ENCODING	23	31	enum	9	Must be 1 0 1 1 1 1 1 1 0.
             
            string[] args = Regex.Split(options, @"\s*[,\s]\s*");

            OpCode op_code = new OpCode { code = instr.opCode };

            if (args.Length != 2)
            {
                log.Error("SOPC instructions should have 2 arguments.");
                return op_code;
            }

            // SSRC0 (argument 1)
            OpInfo ssrc0 = ParseOperand.parseOperand(args[0], OpType.SCALAR_SRC, 1, log);
            if (ssrc0.flags.HasFlag(OpType.LITERAL))
                op_code.literal = ssrc0.value;

            // SSRC1 (argument 2)
            OpInfo ssrc1 = ParseOperand.parseOperand(args[1], OpType.SCALAR_SRC, 2, log);
            if (ssrc1.flags.HasFlag(OpType.LITERAL))
                op_code.literal = ssrc1.value;

            if ((ssrc0.flags.HasFlag(OpType.LITERAL)) && (ssrc1.flags.HasFlag(OpType.LITERAL)))
               log.Error("cannot have two literals");

            op_code.code |= (ssrc1.reg << 8) | ssrc0.reg;

            return op_code;
        }
Exemplo n.º 58
0
        /// <summary>
        /// SOP2 encoding format 
        /// |ENCODING(2)-30|OP(7)-23|SDST(7)-16|SSRC1(8)-8|SSRC0(8)-0|
        /// </summary>
        private static OpCode encodeSOP2(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // SSRC0	0	7	enum	8	Source 0. First operand for the instruction.
            // SSRC1	8	15	enum	8	Source 1. Second operand for instruction. 
            // SDST	    16	22	enum	7	Scalar destination for instruction. Same codes as for SSRC0, above, except that this can use only codes 0 to 127.
            // OP	    23	29	enum	7	Opcode.
            // ENCODING	30	31	enum	2	Must be 1 0.
            
            string[] args = Regex.Split(options, @"\s*[,\s]\s*");

            OpCode op_code = new OpCode { code = instr.opCode };

            if (args.Length != 3)
            {
                log.Error("SOP2 instructions should have 3 arguments.");
                return op_code;
            }

            // SDST (argument 1)
            uint sdst_val = ParseOperand.parseOperand(args[0], OpType.SCALAR_DST, 1, log).value;

            // SSRC0 (argument 2)
            OpInfo ssrc0 = ParseOperand.parseOperand(args[1], OpType.SCALAR_SRC, 2, log);
            if (ssrc0.flags.HasFlag(OpType.LITERAL))
                op_code.literal = ssrc0.value;

            // SSRC1 (argument 3)
            OpInfo ssrc1 = ParseOperand.parseOperand(args[2], OpType.SCALAR_SRC, 3, log);
            if (ssrc1.flags.HasFlag(OpType.LITERAL))
                op_code.literal = ssrc1.value;

            if ((ssrc0.flags.HasFlag(OpType.LITERAL)) && (ssrc1.flags.HasFlag(OpType.LITERAL)))
               log.Error("cannot have two literals");

            op_code.code |= (sdst_val << 16) | (ssrc1.reg << 8) | ssrc0.reg;

            return op_code;
        }
Exemplo n.º 59
0
        /// <summary>
        /// SOP1 encoding format 
        /// |ENCODING(9)-23|SDST(7)-16|OP(8)-8|SSRC0(8)-0|
        /// </summary>
        private static OpCode encodeSOP1(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // SSRC0	0	7	enum	8	Source 0. First operand for the instruction.
            // OP	    8	15	enum	8	0 – 2 reserved.
            // SDST	    16	22	enum	7	Scalar destination for instruction. Same codes as for SSRC0, above, except that this can use only codes 0 to 127.
            // ENCODING	23	31	enum	9	Must be 1 0 1 1 1 1 1 0 1.
            string[] args = Regex.Split(options, @"\s*,\s*");

            int argCt = args.Length;
            if (argCt == 1)
                if (args[0] == "")
                    argCt = 0;

            OpCode op_code = new OpCode { code = instr.opCode };

            switch (instr.name)
            {
                case "s_setpc_b64":
                    if (argCt != 1)
                        {
                            log.Error("s_setpc_b64 should have a jump destination only.(S reg or constant");
                            return op_code;
                        }

                    uint ssrc = ParseOperand.parseOperand(args[0], OpType.SCALAR_SRC, 1, log).value;
                    return new OpCode { code = instr.opCode | ssrc };
                case "s_getpc_b64":
                    if (argCt != 1)
                        {
                            log.Error("s_getpc_b64 takes a 64-bit S reg only.");
                            return op_code;
                        }
                    uint sdst = ParseOperand.parseOperand(args[0], OpType.SCALAR_DST, 1, log).value;
                    return new OpCode { code = instr.opCode | (sdst << 16) };
                case "s_rfe_b64":
                    if (argCt == 0)
                        log.Error("s_rfe_b64 does not take any params.");
                    return op_code;
                case "s_cbranch_join":
                    if (argCt != 1)
                    {
                        log.Error("s_cbranch_join only takes one argument.(the saved CSP value)");
                        return op_code;
                    }
                    uint ssrc2 = ParseOperand.parseOperand(args[0], OpType.SCALAR_SRC, 1, log).value;
                    return new OpCode { code = instr.opCode | ssrc2 };
                case "s_set_gpr_idx_idx":
                    if (argCt != 1)
                    {
                        log.Error("s_set_gpr_idx_idx only takes one argument.(M0[7:0] = S0.U[7:0])");
                        return op_code;
                    }
                    uint ssrc3 = ParseOperand.parseOperand(args[0], OpType.SCALAR_SRC, 1, log).value;
                    return new OpCode { code = instr.opCode | ssrc3 };
                default:
                    if (argCt != 2)
                    {
                        log.Error("SOP1 instructions should have 2 arguments.");
                        return op_code;
                    }

                    // SDST (arg 1) - Destination for instruction.
                    uint sDst = ParseOperand.parseOperand(args[0], OpType.SCALAR_DST, 1, log).value;

                    // SSRC0 (arg 2)
                    OpInfo ssrc0 = ParseOperand.parseOperand(args[1], OpType.SCALAR_SRC, 2, log);
                    if (ssrc0.flags.HasFlag(OpType.LITERAL))
                        op_code.literal = ssrc0.value;

                    op_code.code |= (sDst << 16) | ssrc0.reg;

                    return op_code;
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// SMRD encoding format 
        /// |ENCODING(5)-27|OP(5)-22|SDST(7)-15|SBASE(6)-9|IMM(1)-8|OFFSET(int,8)-0|
        /// </summary>
        private static OpCode encodeSMRD(InstInfo instr, string options, Log log)
        {
            // Field   beg end  dataType  size  notes  (from AMD ISA Manual)
            // OFFSET	0	7	int	    8	Unsigned eight-bit Dword offset to the address specified in SBASE.
            // IMM	    8	8	enum	1	Boolean.[IMM = 0:Specifies an SGPR address that supplies a Dword offset for the memory operation (see enumeration)., IMM = 1:Specifies an 8-bit unsigned Dword offset.]
            // SBASE	9	14	enum	6	Bits [6:1] of an aligned pair of SGPRs specifying {size[15:0], base[47:0]}, where base and size are in Dword units. The low-order bits are in the first SGPR.
            // SDST	    15	21	enum	7	Destination for instruction.
            // OP	    22	26	enum	5	
            // ENCODING	27	31	enum	5	Must be 1 1 0 0 0.

            OpCode op_code = new OpCode { code = instr.opCode };
            
            if (instr.name == "s_dcache_inv")
                return op_code;

            if (instr.name == "s_memtime")
            {
                uint sgpr = ParseOperand.parseOnlySGPR(options, 0, log, OpType.SGPR);
                return (new OpCode { code = instr.opCode | (sgpr << 15) | (1 << 7)});
            }

            string[] args = Regex.Split(options, @"\s*[,\s]\s*");

            if ((args.Length < 2) | (args.Length > 4))
               log.Error("S_Load/S_Buffer should contain 2 to 4 arguments.");

            // SDST (argument 0) - Destination for instruction.
            uint sdst_val = ParseOperand.parseOperand(args[0], OpType.SGPR | OpType.VCC | OpType.TRAP | OpType.M0 | OpType.EXEC, 1, log).value;

            // SBASE (argument 1) - Specifies the SGPR-pair that holds the base byte-address for the fetch.
            uint sbase_op = ParseOperand.parseOperand(args[1], OpType.SGPR | OpType.VCC | OpType.TRAP | OpType.M0 | OpType.EXEC, 2, log).reg;
            if ((sbase_op & 0x01) > 0)
                log.Error("S_Load/S_Buffer must contain an even reg number for the SBASE.");

            // OFFSET (argument 2) - Either holds a ubyte offset or points to a SGPR that contains a byte offset (inline constants not allowed)
            if (args.Length > 2)  // if we don't have an offset then lets not set anything (leave zero)
            {
                OpInfo offset = ParseOperand.parseOperand(args[2], OpType.SCALAR_SRC, 3, log);
                if ((offset.dataDisc & DataDesc.NEGITIVE) != 0)
                    log.Error("offset cannot be negative because it is unsigned");
                if (DataDesc.UINT.HasFlag(offset.dataDisc))
                {
                    // if larger then 256 then use literal value
                    if (offset.value < 256)
                        op_code.code |= (1 << 8) | offset.value;
                    else
                    {
                        op_code.code |= 255;
                        op_code.literal = offset.value;
                    }
                }
                else
                    op_code.code |= offset.reg;
            }

            op_code.code |= (sdst_val << 15) | ((sbase_op >> 1) << 9);

            return op_code;
        }