Example #1
0
 /// <summary>
 /// 加载后需要做的动作
 /// </summary>
 protected override void InnerOnLoading()
 {
     //Local configuration's CSN address is the highest priority option.
     if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CSN"]))
     {
         _tracing.Info("#Use local configuration CSN address...");
         Console.WriteLine("     #Use local configuration CSN address...");
         _isInitialized = true;
         if (_serviceRole != "LGS")
         {
             SystemWorker.Instance.Initialize(_serviceRole, true, null, ConfigurationManager.AppSettings["CSN"]);
         }
         else
         {
             RemoteConfigurationSetting configurationSetting = new RemoteConfigurationSetting();
             configurationSetting.IsCustomizeKJFrameworkConfig       = true;
             configurationSetting.IsSpecific_Customer_Profile_Config = true;
             SystemWorker.Instance.Initialize("LGS", true, configurationSetting, null, ConfigurationManager.AppSettings["CSN"]);
         }
         CoreInnerOnLoading();
         CoreInnerStart();
     }
     else
     {
         _tracing.Info("     #Starting discovery mode and waiting specific event...");
         Console.WriteLine("     #Starting discovery mode and waiting specific event...");
         _inputPin = new DiscoveryInputPin(_monitorPort);
         //Discovery pattern.
         _inputPin.AddNotificationEvent("CSN", delegate(CommonBoradcastProtocol obj)
         {
             if (_isInitialized)
             {
                 return;
             }
             if (obj.Environment != _environment)
             {
                 return;
             }
             _tracing.Info("     #Discovery event had been received, running business component now...");
             Console.WriteLine("     #Discovery event had been received, running business component now...");
             _isInitialized = true;
             if (_serviceRole != "LGS")
             {
                 SystemWorker.Instance.Initialize(_serviceRole, true, null, obj.Value);
             }
             else
             {
                 RemoteConfigurationSetting configurationSetting         = new RemoteConfigurationSetting();
                 configurationSetting.IsCustomizeKJFrameworkConfig       = true;
                 configurationSetting.IsSpecific_Customer_Profile_Config = true;
                 SystemWorker.Instance.Initialize("LGS", true, configurationSetting, null, obj.Value);
             }
             CoreInnerOnLoading();
             CoreInnerStart();
             _tracing.Info("     #Business component run at discovery mode start succeed!");
             Console.WriteLine("     #Business component run at discovery mode start succeed!");
         });
     }
 }
        public static void Build(string[] dlls)
        {
            CompilerParameters opt = new CompilerParameters(new string[] {
                "System.dll", "IICCommonLibrary.dll"
            });

            if (dlls != null)
            {
                foreach (var dll in dlls)
                {
                    opt.ReferencedAssemblies.Add(dll);
                }
            }
            opt.GenerateExecutable      = false;
            opt.TreatWarningsAsErrors   = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory        = true;

            CodeDomProvider provider = CodeDomProvider.CreateProvider("cs");

            StringWriter sw = new StringWriter();

            provider.GenerateCodeFromCompileUnit(CompileUnit, sw, null);
            string output = sw.ToString();

            _tracing.Info(output);
            sw.Close();

            CompilerResults results = provider.CompileAssemblyFromDom(opt, CompileUnit);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                _tracing.Warn("Compilation failed.");
                throw new ApplicationException("Compilation failed.");
            }
            else
            {
                _tracing.Info("completed successfully.");
            }

            Type typeMethodHelper = results.CompiledAssembly
                                    .GetType("Imps.Generics.DynamicTypes.TransparentMethodHelper");

            foreach (var pair in dict)
            {
                RpcGetArgsDelegate getArgs;
                MethodInfo         mi = typeMethodHelper.GetMethod(pair.Key);
                getArgs = (RpcGetArgsDelegate)RpcGetArgsDelegate.CreateDelegate(
                    typeof(RpcGetArgsDelegate), mi);
                pair.Value.GetArgs = getArgs;
            }
        }
Example #3
0
        private DatabaseOperationContext Prepare(string info, string spName, string[] parameters, object[] values)
        {
            DatabaseOperationContext ctx = new DatabaseOperationContext();

            ctx.Info       = info;
            ctx.SpName     = spName;
            ctx.Parameters = parameters;
            ctx.Values     = values;
            ctx.Ex         = null;
            ctx.Watch      = Stopwatch.StartNew();

            if (parameters != null && values != null && parameters.Length != values.Length)
            {
                string msg = string.Format("{0} Parameters({1}) != Values({2})", spName, parameters.Length, values.Length);
                throw new InvalidOperationException(msg);
            }

            ctx.Operation = GetInnerOperation();
            TracingManager.Info(
                delegate() {
                _tracing.Info(info + ":\r\n" + ctx.Operation.FormatSql(spName, parameters, values));
            }
                );

            ctx.Observer = GetObserverItem(spName);

            _perfCounters.CommandExecutedTotal.Increment();
            _perfCounters.CommandExecutedPerSec.Increment();
            return(ctx);
        }
Example #4
0
        /// <summary>
        ///     初始化内存申请器
        /// </summary>
        /// <exception cref="ArgumentException">内部成员变量值不符合要求</exception>
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }
            if (SegmentSize > 1024 || SegmentSize < 64)
            {
                throw new ArgumentException("Value range: 64~1024.");
            }
            if (SegmentSize % 64 != 0)
            {
                throw new ArgumentException("Value *MUST* be 64 multiples!");
            }
            //max 10mb.
            int totalSize = (int)(SegmentSize * Multiples);

            _data = (byte *)Marshal.AllocHGlobal(totalSize);
            //create segments.
            lock (_lockObj)
            {
                for (int i = 0; i < Multiples; i++)
                {
                    _segments.Push(new MemorySegment(_data, (uint)(i * SegmentSize), SegmentSize));
                }
                GC.Collect();
            }
            _initialized = true;
            if (AllowPrintInfo)
            {
                _tracing.Info(string.Format("\r\n[KJFramework.Message Unmanaged Memory Info]\r\n#Unmanaged Memory: {0} bytes.\r\n#Segments: {1}.", totalSize, Multiples));
            }
        }
Example #5
0
        /// <summary>
        ///    使用一个装配清单来下载远程的KPP列表
        ///     <para>* 这要求装配清单中的每一个完整的APP名称都要由以下格式来组成</para>
        ///     <para>* PackageName-Version</para>
        /// </summary>
        /// <param name="workRoot">当前应用程序所在的目录</param>
        /// <param name="installingListFile">装配清单文件</param>
        /// <returns>返回已下载后放置KPP的本地目录路径</returns>
        /// <exception cref="WebException">无法下载远程指定的KPP</exception>
        /// <exception cref="FormatException">错误的KPP包名格式</exception>
        /// <exception cref="RemotingException">与远程KIS通信失败</exception>
        /// <exception cref="JsonReaderException ">错误的JSON格式</exception>
        public string DownloadFromList(string workRoot, string installingListFile)
        {
            _tracing.Info("\t#Opened remoting downloading package mode!");
            if (!File.Exists(installingListFile))
            {
                throw new FileNotFoundException(string.Format("#Current KAE installing package list file could not be found! {0}", installingListFile));
            }
            _tracing.Info("\t\t#Searching local KAE package...");
            string storeDir = Path.Combine(workRoot, "Applications");

            if (!Directory.Exists(storeDir))
            {
                Directory.CreateDirectory(storeDir);
            }
            List <string> files = Directory.GetFiles(workRoot, "*.kpp", SearchOption.AllDirectories).Select(Path.GetFileNameWithoutExtension).ToList();

            _tracing.Info("\t\t#Analyzing installing package file...");
            PackageList obj = JsonConvert.DeserializeObject <PackageList>(File.ReadAllText(installingListFile));

            if (obj == null || obj.Packages == null || obj.Packages.Count == 0)
            {
                throw new Exception(string.Format("#Could not get any information by curent KAE installing package list file: {0}", installingListFile));
            }
            foreach (Package package in obj.Packages)
            {
                if (files.Contains(package.Name))
                {
                    _tracing.Info("\t\t\t#Skipping existed package: {0}.", package.Name);
                    continue;
                }
                string[] args = package.Name.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                if (args.Length != 2)
                {
                    throw new FormatException(string.Format("#Bad format package name: {0}. It MUST be format like that. \"name-version\"", package.Name));
                }
                PackageInfo packageInfo = ((IRemotingKISProxy)KAESystemInternalResource.Factory.GetResource(KAESystemInternalResource.KISProxy)).GetReallyRemotingAddress(args[0], args[1]);
                if (packageInfo == null)
                {
                    throw new RemotingException(string.Format("#Could not get any information from the remoting KIS by given package name: {0}", package.Name));
                }
                //Just store it under the first level of folder.
                string tempFileLocation = Path.Combine(storeDir, Path.GetFileName(packageInfo.Url));
                _tracing.Info("\t\t#Downloading remoting KAE package: {0}...", packageInfo.Url);
                InnerDownload(packageInfo.Url, tempFileLocation);
            }
            return(storeDir);
        }
Example #6
0
 /// <summary>
 ///     发送一个请求消息
 /// </summary>
 /// <param name="message">请求消息</param>
 public override void SendRequest(MetadataContainer message)
 {
     if (message == null)
     {
         return;
     }
     Identity.IsRequest = true;
     if (_fixedMsgIdentity)
     {
         message.SetAttribute(0x00, new MessageIdentityValueStored(_msgIdentity));
     }
     message.SetAttribute(0x01, new TransactionIdentityValueStored(Identity));
     message.SetAttribute(0x02, new DateTimeValueStored(_lease.ExpireTime));
     message.SetAttribute(0x03, new GuidValueStored(KPPUniqueId));
     _request = message;
     if (!_channel.IsConnected)
     {
         _tracing.Warn("Cannot send a response message to {0}, because target msg channel has been disconnected.", _channel.RemoteEndPoint);
         TransactionManager.Remove(Identity);
         FailedHandler(null);
         return;
     }
     try
     {
         int sendCount;
         //send failed.
         if ((sendCount = _channel.Send(message)) < 0)
         {
             TransactionManager.Remove(Identity);
             _channel.Disconnect();
             FailedHandler(null);
             return;
         }
         //calc REQ time.
         RequestTime = DateTime.Now;
         _tracing.Info("SendCount: {0}\r\nL: {1}\r\nR: {2}\r\n{3}", sendCount, _channel.LocalEndPoint, _channel.RemoteEndPoint, message.ToString());
     }
     catch (System.Exception ex)
     {
         TransactionManager.Remove(Identity);
         _channel.Disconnect();
         FailedHandler(null);
     }
 }
Example #7
0
 /// <summary>
 ///     发送一个请求消息
 /// </summary>
 /// <param name="message">请求消息</param>
 public override void SendRequest(BaseMessage message)
 {
     if (message == null)
     {
         return;
     }
     if (_fixedMsgIdentity)
     {
         message.MessageIdentity = _msgIdentity;
     }
     message.TransactionIdentity           = Identity;
     message.TransactionIdentity.IsRequest = true;
     message.ExpireTime  = _lease.ExpireTime;
     message.KPPUniqueId = KPPUniqueId;
     _request            = message;
     if (!_channel.IsConnected)
     {
         _tracing.Warn("Cannot send a response message to {0}, because target msg channel has been disconnected.", _channel.RemoteEndPoint);
         TransactionManager.Remove(Identity);
         FailedHandler(null);
         return;
     }
     try
     {
         int sendCount;
         //send failed.
         if ((sendCount = _channel.Send(message)) < 0)
         {
             TransactionManager.Remove(Identity);
             _channel.Disconnect();
             FailedHandler(null);
             return;
         }
         //calc REQ time.
         RequestTime = DateTime.Now;
         _tracing.Info("SendCount: {0}\r\nL: {1}\r\nR: {2}\r\n{3}", sendCount, _channel.LocalEndPoint, _channel.RemoteEndPoint, message.ToString());
     }
     catch
     {
         TransactionManager.Remove(Identity);
         _channel.Disconnect();
         FailedHandler(null);
     }
 }
Example #8
0
        /// <param name="saveProjectDelegate">T1 = path, T2 = content</param>
        internal void Execute(
            IEnumerable <IProject> applicationProjects,
            ITracing tracing,
            Action <string, string> saveProjectDelegate,
            Func <IProject, string> loadProjectDelegate)
        {
            string report;

            var(projectPackages, highestVersions) = DeterminePackages(applicationProjects, loadProjectDelegate);

            if (_settingConsolidatePackageVersions &&
                !string.IsNullOrWhiteSpace(report = GetPackagesWithMultipleVersionsReport(projectPackages)))
            {
                tracing.Info(
                    "Multiple versions exist for one or more NuGet packages within the solution. Intent will now automatically " +
                    "upgrade any lower versions to the highest installed version within the solution. To disable this behaviour " +
                    $"change the 'Consolidate Package Versions' option in Intent in the {Identifier} module configuration." +
                    $"{Environment.NewLine}" +
                    $"{Environment.NewLine}" +
                    $"{report}");

                ConsolidatePackageVersions(projectPackages, highestVersions);
            }

            foreach (var projectPackage in projectPackages)
            {
                if (!projectPackage.RequestedPackages.Any())
                {
                    continue;
                }

                var updatedProjectContent = projectPackage.Processor.InstallPackages(
                    projectContent: projectPackage.Content,
                    requestedPackages: projectPackage.RequestedPackages,
                    installedPackages: projectPackage.InstalledPackages,
                    projectName: projectPackage.Name,
                    tracing: tracing);
                saveProjectDelegate(projectPackage.FilePath, updatedProjectContent);
            }

            if (_settingWarnOnMultipleVersionsOfSamePackage &&
                !_settingConsolidatePackageVersions &&
                !string.IsNullOrWhiteSpace(report = GetPackagesWithMultipleVersionsReport(projectPackages)))
            {
                tracing.Warning(
                    "Multiple versions exist for one or more NuGet packages within the solution. You should consider " +
                    "consolidating these package versions within Visual Studio or alternatively enable the 'Consolidate " +
                    $"Package Versions' option in Intent in the {Identifier} module configuration." +
                    $"{Environment.NewLine}" +
                    $"{Environment.NewLine}" +
                    $"{report}");
            }
        }
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs <List <BaseMessage> > e)
        {
            IMessageTransportChannel <BaseMessage> msgChannel = (IMessageTransportChannel <BaseMessage>)sender;

            foreach (BaseMessage message in e.Target)
            {
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                if (message is CSNGetKeyDataResponseMessage || message is CSNGetDataTableResponseMessage || message is CSNGetPartialConfigResponseMessage)
                {
                    _transactionManager.Active(message.TransactionIdentity, message);
                }
            }
        }
 /// <summary>
 ///     发送一个请求消息
 /// </summary>
 /// <param name="message">请求消息</param>
 public override void SendRequest(ThriftMessage message)
 {
     if (message == null) return;
     message.Identity.SequenceId = (uint) SequenceId;
     if (!_channel.IsConnected)
     {
         _tracing.Error(string.Format("Cannot send a Thrift protocol REQ message to {0}, because target msg channel has been disconnected.", _channel.RemoteEndPoint));
         return;
     }
     try
     {
         //send failed.
         if (_channel.Send(message) < 0)
         {
             _tracing.Error("#REQ message send count < 0. #Identity: {0}", message.Identity);
             TransactionManager.Remove(Identity);
             _channel.Disconnect();
             FailedHandler(null);
             return;
         }
         //calc REQ time.
         RequestTime = DateTime.Now;
         //30s
         GetLease().Change(DateTime.Now.AddSeconds(30));
         string msgInfo;
         if (!(message is InsertNewRowsRequestMessage)) msgInfo = message.ToString();
         else msgInfo = (Global.NeedLogBatchInsert ? message.ToString() : (Global.BatchInsertNotification + "\r\n" + message.Identity.SequenceId));
         _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", _channel.LocalEndPoint, _channel.RemoteEndPoint, msgInfo);
     }
     catch(Exception ex)
     {
         _tracing.Error(ex, null);
         TransactionManager.Remove(Identity);
         _channel.Disconnect();
         FailedHandler(null);
     }
 }
        //new message arrived.
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs <System.Collections.Generic.List <ThriftMessage> > e)
        {
            IMessageTransportChannel <ThriftMessage> msgChannel = (IMessageTransportChannel <ThriftMessage>)sender;

            foreach (ThriftMessage message in e.Target)
            {
                if (message == null)
                {
                    continue;
                }
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                //rebuilds corresponding TransactionIdentity for current RSP message.
                TransactionIdentity identity = IdentityHelper.Create((IPEndPoint)msgChannel.LocalEndPoint, (int)message.Identity.SequenceId, false);
                _transactionManager.Active(identity, message);
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            ServiceSettings.InitService("IICCommon");
            ITracing tracing = TracingManager.GetTracing(typeof(Program));

            tracing.Info("test");
            LinkedNode <string> linkedNode = new LinkedNode <string>();

            linkedNode.Value = "1";
            linkedNode.AddNext("2");
            linkedNode.AddNext("3");
            foreach (string str in linkedNode.GetValues())
            {
                Console.WriteLine(str);
            }
            Console.ReadLine();
        }
Example #13
0
        public static void process()
        {
            int a   = 2;
            int b   = 3;
            int sum = a + b;

            _tracing.Info(a.ToString() + "+" + b.ToString() + "=" + sum.ToString());

            int d     = 0;
            int split = 0;

            try {
                split = sum / d;
            }catch (Exception ex)
            {
                _tracing.Error(ex, "can not split by zero .");
            }
        }
        protected override void CoreInnerStart()
        {
            int port = int.Parse(SystemWorker.Instance.ConfigurationProxy.GetField("CoinAPI", "ServicePort"));

            _tracing.Info("     #Get client-port config succeed, port: " + port);
            Console.WriteLine("     #Get client-port config succeed, port: " + port);
            _hostChannel = new TcpHostTransportChannel(port);
            _tracing.Info("     #Initialize TCP host channel succeed!");
            Console.WriteLine("     #Initialize TCP host channel succeed!");
            if (!_hostChannel.Regist())
            {
                _tracing.Critical("     #Regist TCP port {0} failed!", port);
                Console.WriteLine(string.Format("       #Regist TCP port {0} failed!", port));
                throw new Exception(string.Format("     #Regist TCP port {0} failed!", port));
            }
            _tracing.Info("     #Regist TCP host channel succeed!");
            Console.WriteLine("     #Regist TCP host channel succeed!");
            _hostChannel.ChannelCreated += ChannelCreated;
        }
        //new message arrived.
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs <List <MetadataContainer> > e)
        {
            IMessageTransportChannel <MetadataContainer> msgChannel = (IMessageTransportChannel <MetadataContainer>)sender;

            foreach (MetadataContainer message in e.Target)
            {
                if (message == null)
                {
                    continue;
                }
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                TransactionIdentity identity;
                if (!message.IsAttibuteExsits(0x01))
                {
                    identity = msgChannel.GenerateRequestIdentity(0U);
                }
                else
                {
                    identity = message.GetAttribute(0x01).GetValue <TransactionIdentity>();
                }
                //response.
                if (!identity.IsRequest)
                {
                    _transactionManager.Active(identity, message);
                    continue;
                }
                //create transaction by IsOneway flag.
                IMessageTransaction <MetadataContainer> transaction = new MetadataMessageTransaction(_channel)
                {
                    NeedResponse       = !identity.IsOneway,
                    TransactionManager = _transactionManager,
                    Identity           = identity,
                    Request            = message
                };
                transaction.GetLease().Change(message.GetAttributeAsType <DateTime>(0x02));
                NewTransactionHandler(new LightSingleArgEventArgs <IMessageTransaction <MetadataContainer> >(transaction));
            }
        }
        //new message arrived.
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs <System.Collections.Generic.List <BaseMessage> > e)
        {
            IMessageTransportChannel <BaseMessage> msgChannel = (IMessageTransportChannel <BaseMessage>)sender;

            foreach (BaseMessage message in e.Target)
            {
                if (message == null)
                {
                    continue;
                }
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                TransactionIdentity identity;
                if (message.TransactionIdentity == null)
                {
                    identity = msgChannel.GenerateRequestIdentity(0U);
                }
                else
                {
                    identity = message.TransactionIdentity;
                }
                //response.
                if (!identity.IsRequest)
                {
                    _transactionManager.Active(identity, message);
                    continue;
                }
                //create transaction by IsOneway flag.
                IMessageTransaction <BaseMessage> transaction = new BusinessMessageTransaction(_channel)
                {
                    NeedResponse       = !identity.IsOneway,
                    TransactionManager = _transactionManager,
                    Identity           = identity,
                    Request            = message
                };
                transaction.GetLease().Change(message.ExpireTime);
                NewTransactionHandler(new LightSingleArgEventArgs <IMessageTransaction <BaseMessage> >(transaction));
            }
        }
Example #17
0
        public string InstallPackages(
            string projectContent,
            Dictionary <string, NuGetPackage> requestedPackages,
            Dictionary <string, NuGetPackage> installedPackages,
            string projectName,
            ITracing tracing)
        {
            var document = XDocument.Parse(projectContent);

            var(prefix, namespaceManager, namespaceName) = document.GetNamespaceManager();

            var packageReferenceItemGroup = document.XPathSelectElement($"/{prefix}:Project/{prefix}:ItemGroup[{prefix}:PackageReference]", namespaceManager);

            // Try add after last ItemGroup, otherwise last PropertyGroup
            if (packageReferenceItemGroup == null)
            {
                var element = document.XPathSelectElements($"/{prefix}:Project/{prefix}:ItemGroup", namespaceManager).LastOrDefault() ??
                              document.XPathSelectElements($"/{prefix}:Project/{prefix}:PropertyGroup", namespaceManager).LastOrDefault();
                element?.AddAfterSelf(packageReferenceItemGroup = new XElement(XName.Get("ItemGroup", namespaceName)));
            }

            // Otherwise, add to Project element
            if (packageReferenceItemGroup == null)
            {
                var projectElement = document.XPathSelectElement($"/{prefix}:Project", namespaceManager);
                if (projectElement == null)
                {
                    throw new Exception("Project element not found.");
                }

                projectElement.AddFirst(packageReferenceItemGroup = new XElement(XName.Get("ItemGroup", namespaceName)));
            }

            foreach (var requestedPackage in requestedPackages)
            {
                var packageId = requestedPackage.Key;
                var package   = requestedPackage.Value;

                var packageReferenceElement = packageReferenceItemGroup.XPathSelectElement($"{prefix}:PackageReference[@Include='{packageId}']", namespaceManager);
                if (packageReferenceElement == null)
                {
                    tracing.Info($"Installing {packageId} {package.Version} into project {projectName}");

                    packageReferenceItemGroup.Add(packageReferenceElement = new XElement(
                                                      XName.Get("PackageReference", namespaceName),
                                                      new XAttribute("Include", packageId),
                                                      new XElement(XName.Get("Version", namespaceName), package.Version)));
                }

                var versionElement = packageReferenceElement.XPathSelectElement($"{prefix}:Version", namespaceManager);
                if (versionElement == null)
                {
                    throw new Exception("Missing version element from PackageReference element.");
                }

                if (SemanticVersion.Parse(versionElement.Value) >= package.Version)
                {
                    continue;
                }

                tracing.Info($"Upgrading {packageId} from {versionElement.Value} to {package.Version} in project {projectName}");
                versionElement.SetValue(package.Version);
            }

            SortAlphabetically(packageReferenceItemGroup);
            return(Format(document));
        }
Example #18
0
        //Try to initializes internal statements.
        private void Initialize(string connectionStr)
        {
            _arguments = connectionStr.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(v => v.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries)).ToDictionary(v => v[0].Trim(), vs => vs[1]);
            string zkStr, zkTimeoutStr;

            if (!_arguments.TryGetValue("zk", out zkStr))
            {
                throw new ArgumentException("#Lost KEY argument: \"zk\"");
            }
            TimeSpan zkTimeout;

            if (!_arguments.TryGetValue("zkTimeout", out zkTimeoutStr))
            {
                zkTimeout = new TimeSpan(0, 0, 30);
            }
            else
            {
                zkTimeout = TimeSpan.Parse(zkTimeoutStr);
            }
            string portStr;

            if (!_arguments.TryGetValue("tPort", out portStr))
            {
                _tPort = 9090;
            }
            else
            {
                _tPort = int.Parse(portStr);
            }
            //MEMORY SETTINGS
            string memSegSizeStr, memSegMultiplesStr;
            int    memSegSize, memSegMultiples;

            if (!_arguments.TryGetValue("memSegSize", out memSegSizeStr))
            {
                memSegSize = 256;
            }
            else
            {
                memSegSize = int.Parse(memSegSizeStr);
            }
            if (!_arguments.TryGetValue("memSegMultiples", out memSegMultiplesStr))
            {
                memSegMultiples = 100000;
            }
            else
            {
                memSegMultiples = int.Parse(memSegMultiplesStr);
            }
            ThriftProtocolMemoryAllotter.InitializeEnvironment((uint)memSegSize, (uint)memSegMultiples);
            //NETWORK SETTINGS
            int    minConnection, maxConnection;
            string minConnectionStr, maxConnectionStr;

            if (!_arguments.TryGetValue("minConnection", out minConnectionStr))
            {
                minConnection = 1;
            }
            else
            {
                minConnection = int.Parse(minConnectionStr);
            }
            if (!_arguments.TryGetValue("maxConnection", out maxConnectionStr))
            {
                maxConnection = 3;
            }
            else
            {
                maxConnection = int.Parse(maxConnectionStr);
            }
            _connectionPool = new ThriftProtocolConnectionPool(minConnection, maxConnection);
            bool   allowPrintDumpInfo;
            string allowPrintDumpInfoStr;

            if (!_arguments.TryGetValue("allowPrintDumpInfo", out allowPrintDumpInfoStr))
            {
                allowPrintDumpInfo = false;
            }
            else
            {
                allowPrintDumpInfo = bool.Parse(allowPrintDumpInfoStr);
            }
            Global.AllowedPrintDumpInfo = allowPrintDumpInfo;

            _zkClient = new ZooKeeper(zkStr, zkTimeout, new ZooKeeperWatcher(WaitForZooKeeperInitialization));
            if (!_zooKeeperInitLock.WaitOne(new TimeSpan(0, 0, 30)))
            {
                throw new ZooKeeperInitializationException();
            }
            _tracing.Info("#Sync remote ZooKeeper state succeed.");
            UpdateRegionServers(null);
        }
Example #19
0
        public void SendRequest(JsonRpcRequest rpcRequest, int timeout, Action <JsonRpcResponse> callback)
        {
            // Console.WriteLine("发送请求11111111111111"+DateTime.Now.ToShortDateString());
            TracingManager.Info(
                delegate()
            {
                string module = null;
                string action = null;
                if (rpcRequest.Header != null)
                {
                    module = rpcRequest.Header["UU-REQUEST-MODULE"] == null ? "" : rpcRequest.Header["UU-REQUEST-MODULE"];
                    action = rpcRequest.Header["UU-REQUEST-ACTION"] == null ? "" : rpcRequest.Header["UU-REQUEST-ACTION"];
                }
                _tracing.Info(string.Format("jsonrpc request:uri={0} module={1} action={2}\r\nrequestbody:{3}",
                                            rpcRequest.ServiceUri, module, action, rpcRequest.ReqBody));
            }
                );
            _sericeUri = rpcRequest.ServiceUri;
            _callback  = callback;

            _webRequest             = HttpWebRequest.Create(new Uri(_sericeUri));
            _webRequest.Method      = "POST";
            _webRequest.Proxy       = null;
            _webRequest.ContentType = "application/json";
            _webRequest.Headers.Add(HttpRequestHeader.From, rpcRequest.FromComputer);
            _webRequest.Headers.Add(HttpRequestHeader.Pragma, rpcRequest.FromService);

            if (rpcRequest.Header != null && rpcRequest.Header.Count > 0)
            {
                foreach (string key in rpcRequest.Header.AllKeys)
                {
                    _webRequest.Headers.Add(key, rpcRequest.Header[key]);
                }
            }

            byte[] buffer = null;
            if (rpcRequest.ReqBody == null)
            {
                _webRequest.ContentLength = 0;
            }
            else
            {
                buffer = Encoding.UTF8.GetBytes(rpcRequest.ReqBody);//Request.BodyBuffer.GetByteArray();
                _webRequest.ContentLength = buffer.Length;
            }

            timeout = timeout > 0 ? timeout : _timeOut;

            if (timeout > 0)
            {
                _waitHandle       = new ManualResetEvent(false);
                _registeredHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(TimeoutCallback), this, timeout, true);
            }
            if (_webRequest.ContentLength == 0)
            {
                _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
            }
            else
            {
                _webRequest.BeginGetRequestStream(
                    delegate(IAsyncResult asyncResult)
                {
                    JsonRpcHttpClientTransaction trans = (JsonRpcHttpClientTransaction)asyncResult.AsyncState;
                    try
                    {
                        WebRequest webReq = trans._webRequest;

                        Stream stream = webReq.EndGetRequestStream(asyncResult);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                        webReq.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
                    }
                    catch (Exception ex)
                    {
                        var rpcResonse = new JsonRpcResponse(JsonRpcErrorCode.SendFailed, null, new JsonRpcException(_sericeUri, "send failed", ex), 0);
                        trans.OnCallback(rpcResonse);
                    }
                },
                    this
                    );
            }
        }
Example #20
0
 public override void Write(string message)
 {
     _tracing.Info(message);
 }
Example #21
0
        public string InstallPackages(
            string projectContent,
            Dictionary <string, NuGetPackage> requestedPackages,
            Dictionary <string, NuGetPackage> installedPackages,
            string projectName,
            ITracing tracing)
        {
            var document = XDocument.Parse(projectContent);

            var packageReferenceItemGroup = document.XPathSelectElement("Project/ItemGroup[PackageReference]");

            if (packageReferenceItemGroup == null)
            {
                var projectElement = document.XPathSelectElement("Project");
                if (projectElement == null)
                {
                    throw new Exception("Project element not found.");
                }

                projectElement.Add(packageReferenceItemGroup = new XElement("ItemGroup"));
            }

            foreach (var requestedPackage in requestedPackages)
            {
                var packageId = requestedPackage.Key;
                var package   = requestedPackage.Value;

                var packageReferenceElement = packageReferenceItemGroup.XPathSelectElement($"PackageReference[@Include='{packageId}']");
                if (packageReferenceElement == null)
                {
                    tracing.Info($"Installing {packageId} {package.Version} into project {projectName}");
                    packageReferenceItemGroup.Add(packageReferenceElement = new XElement("PackageReference",
                                                                                         new XAttribute("Include", packageId),
                                                                                         new XAttribute("Version", package.Version)));
                }

                if (package.PrivateAssets.Any())
                {
                    var privateAssetsElement = packageReferenceElement.XPathSelectElement("PrivateAssets");
                    if (privateAssetsElement == null)
                    {
                        packageReferenceElement.Add(privateAssetsElement = new XElement("PrivateAssets"));
                    }

                    privateAssetsElement.SetValue(package.PrivateAssets.Aggregate((x, y) => x + "; " + y));
                }


                if (package.IncludeAssets.Any())
                {
                    var includeAssetsElement = packageReferenceElement.XPathSelectElement("IncludeAssets");
                    if (includeAssetsElement == null)
                    {
                        packageReferenceElement.Add(includeAssetsElement = new XElement("IncludeAssets"));
                    }

                    includeAssetsElement.SetValue(package.IncludeAssets.Aggregate((x, y) => x + "; " + y));
                }

                var versionAttribute = packageReferenceElement.Attributes().SingleOrDefault(x => x.Name == "Version");
                if (versionAttribute == null)
                {
                    throw new Exception("Missing version attribute from PackageReference element.");
                }

                if (SemanticVersion.Parse(versionAttribute.Value) >= package.Version)
                {
                    continue;
                }

                tracing.Info($"Upgrading {packageId} from {versionAttribute.Value} to {package.Version} in project {projectName}");
                versionAttribute.SetValue(package.Version);
            }

            SortAlphabetically(packageReferenceItemGroup);
            return(Format(document));
        }
Example #22
0
 public void Info(string message) => _tracing.Info($"{_prefix}{message}");
Example #23
0
        public static TInterface CreateInterface <TInterface>(string ip)
            where TInterface : class
        {
            object obj;
            Type   tInterface = typeof(TInterface);

            if (dict.TryGetValue(tInterface, out obj))
            {
                return(obj as TInterface);
            }

            MethodInfo[] misInterface = tInterface.GetMethods(BindingFlags.Public
                                                              | BindingFlags.Instance);
            List <MethodInfo> misInterfaceList = new List <MethodInfo>();

            foreach (var item in misInterface)
            {
                if (item.IsSpecialName == false)
                {
                    misInterfaceList.Add(item);
                }
            }

            CodeCompileUnit CompileUnit = new CodeCompileUnit();

            CompileUnit.ReferencedAssemblies.Add(typeof(TInterface).Assembly.ManifestModule.ToString());
            CodeNamespace aName = new CodeNamespace("Imps.Generics.DynamicTypes");

            CompileUnit.Namespaces.Add(aName);
            aName.Imports.Add(new CodeNamespaceImport("System"));
            aName.Imports.Add(new CodeNamespaceImport("Imps.Services.CommonV4"));

            string className          = string.Format("{0}_Proxy", tInterface.Name);
            CodeTypeDeclaration proxy = new CodeTypeDeclaration(className);

            aName.Types.Add(proxy);
            proxy.BaseTypes.Add(typeof(TInterface));

            CodeMemberField field_ip = new CodeMemberField(typeof(string), "_ip");

            proxy.Members.Add(field_ip);

            CodeConstructor con = new CodeConstructor();

            con.Attributes = MemberAttributes.Public;
            CodeFieldReferenceExpression field_ip_ref
                = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_ip");

            con.Statements.Add(new CodeAssignStatement(field_ip_ref, new CodePrimitiveExpression(ip)));
            proxy.Members.Add(con);


            foreach (var item in misInterfaceList)
            {
                CreateMethod(aName, proxy, item, typeof(TInterface));
            }
            CompilerParameters opt = new CompilerParameters(new string[] {
                "System.dll",
                "IICCommonLibrary.dll"
            });

            opt.GenerateExecutable      = false;
            opt.TreatWarningsAsErrors   = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory        = true;

            CompilerResults results;
            CodeDomProvider provider = CodeDomProvider.CreateProvider("cs");

            StringWriter sw = new StringWriter();

            provider.GenerateCodeFromCompileUnit(CompileUnit, sw, null);
            string output = sw.ToString();

            _tracing.Info(output);
            sw.Close();

            results = provider.CompileAssemblyFromDom(opt, CompileUnit);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                _tracing.Warn("Compilation failed.");
                throw new ApplicationException("Compilation failed.");
            }
            else
            {
                _tracing.Info("completed successfully.");
            }

            obj = results.CompiledAssembly
                  .CreateInstance(string.Format("{0}.{1}", aName.Name, proxy.Name));
            dict[tInterface] = obj;
            return(obj as TInterface);
        }