/// <summary> /// 启动容器。 /// </summary> public void Start() { //扫描配置信息 string application = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "application.properties"); if (!File.Exists(application)) { throw new FileNotFoundException(string.Format("未找到{0}文件。", application)); } Properties = new PropertiesUtil(application);//创建properties文件解析工具,并解析application.properties string business = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "business"); if (!Directory.Exists(business)) { Directory.CreateDirectory(business); } string[] dlls = Directory.GetFiles(business, "*.*", SearchOption.AllDirectories); if (dlls == null || dlls.Length <= 0) { return; } ScanConfigurationAttribute(dlls); ScanDataAccessAttribute(dlls); ScanBusinessAttribute(dlls); ScanContractAttribute(dlls); ScanBeanAttribute(dlls); ScanResource(dlls); }
/// <summary> /// Metodo para rotear faxes para os usuarios de destino /// </summary> /// <param name="fax"></param> /// <param name="dadosFaxDTO"></param> private void routToUser(Fax fax, DadosFaxDTO dadosFaxDTO) { if (Directory.Exists(PropertiesUtil.getInstance().getProperties("dir_xml_processados"))) { User user = userService.findUser(dadosFaxDTO.RoutingCode); if (user != null) { fax.BillingCode1 = dadosFaxDTO.Billinfo1; fax.BillingCode2 = dadosFaxDTO.Billinfo2; fax.FromName = dadosFaxDTO.Comments; fax.UserComments = dadosFaxDTO.FromName; fax.ToName = dadosFaxDTO.RoutingCode; fax.ToFaxNumber = "990000"; fax.Save(BoolType.True); fax.RouteToUser(user, "XML2URAFAX"); xmlService.moveXMLProcessed(StringUtils.pathXMLSouce(dadosFaxDTO.codigoFax)); } else { Logger.LOGGER_INF("Usuário com routing code {0} não encontrado.".Replace("{0}", dadosFaxDTO.RoutingCode)); } } else { Logger.LOGGER_ERROR("Não é possível mover arquivos XML, propriedade dir_xml_processados não configurado."); } }
private ConfigurationSingleton() { NameValueCollection props = PropertiesUtil.LoadProperty(); this.AppName = props[APP_NAME_PROP]; this.AppVersion = props[APP_VERSION_PROP]; }
/// <summary> /// Conversor de string XML para objeto de fax /// </summary> /// <param name="nomeArquivo"></param> /// <returns>DadosFaxDTO</returns> public DadosFaxDTO mapperXMLtoObject(String nomeArquivo) { DadosFaxDTO dadosFaxDTO = null; StringBuilder arquivo = new StringBuilder(); arquivo.Append(PropertiesUtil.getInstance().getProperties("dir_xml_analisar")); arquivo.Append("\\"); arquivo.Append(nomeArquivo); arquivo.Append(".xml"); if (!File.Exists(StringUtils.pathXMLSouce(nomeArquivo))) { Logger.LOGGER_INF("Arquivo {0}.xml não encontrado.".Replace("{0}", nomeArquivo)); return(null); } XmlSerializer xmlSerializer = new XmlSerializer(typeof(DadosFaxDTO)); using (Stream stream = new FileStream(arquivo.ToString(), FileMode.Open)) { dadosFaxDTO = (DadosFaxDTO)xmlSerializer.Deserialize(stream); } return(dadosFaxDTO); }
public static IDBAdapter GetDefaultDBAdapter() { try { IDictionary <string, string> prop = PropertiesUtil.LoadProperty(DB_FACTORY_PROPERTY_URL); String defaultDBClass = prop[DEFAULT_DB_CLASS_PROP]; Console.WriteLine("DefaultDBClass ==> " + defaultDBClass); Type type = Type.GetType(defaultDBClass); return((IDBAdapter)Activator.CreateInstance(type)); } catch (Exception e) { Console.WriteLine(e.ToString()); return(null); } }
/// <summary> /// Metodo para mover XML nao processado pela rotina com base no ciclo de vida /// configurado para faxes nao processados /// </summary> public void moveXMLDiscarded() { int faxAge = 0; if (String.IsNullOrEmpty(PropertiesUtil.getInstance().getProperties("xml_move_age"))) { Logger.LOGGER_ERROR("Propriedade xml_move_age não configurada."); return; } try { faxAge = Int32.Parse(PropertiesUtil.getInstance().getProperties("xml_move_age")); } catch (Exception e) { Logger.LOGGER_ERROR("Propriedade xml_move_age não configurada com valor numérico."); Logger.LOGGER_ERROR(e.Message); } if (Directory.Exists(PropertiesUtil.getInstance().getProperties("dir_xml_descartado"))) { string[] files = Directory.GetFiles(PropertiesUtil.getInstance().getProperties("dir_xml_analisar")); foreach (string fileSource in files) { DateTime createDate = File.GetCreationTime(fileSource); DateTime xmlAge = DateTime.Now; xmlAge = xmlAge.AddDays(faxAge * (-1)); if (xmlAge >= createDate) { try { String destFile = Path.Combine(PropertiesUtil.getInstance().getProperties("dir_xml_descartado"), System.IO.Path.GetFileName(fileSource)); File.Delete(destFile); File.Move(fileSource, destFile); } catch (IOException e) { Logger.LOGGER_ERROR("Erro ao tentar mover arquivo {0} para o diretório XML_Descartados.".Replace("{0}", fileSource)); Logger.LOGGER_ERROR(e.Message); } } } } else { Logger.LOGGER_ERROR("Não é possível mover arquivos XML, propriedade dir_xml_analisar não está configurada corretamente."); } }
/// <summary> /// Metodo para mover arquivos XML processados pela rotina /// </summary> /// <param name="sourceFile"></param> public void moveXMLProcessed(String sourceFile) { try { String destFile = Path.Combine(PropertiesUtil.getInstance().getProperties("dir_xml_processados"), System.IO.Path.GetFileName(sourceFile)); File.Delete(destFile); File.Move(sourceFile, destFile); } catch (IOException e) { Logger.LOGGER_ERROR("Erro ao tentar mover arquivo {0} para o diretório XML_Processados.".Replace("{0}", sourceFile)); Logger.LOGGER_ERROR(e.Message); } }
public static IServiceStackAbstractFactory CreateServiceFactory() { IDictionary <string, string> props = PropertiesUtil.LoadProperty("./AbstractFactoryConfiguration.properties"); string factoryClass = props["serviceProductImplClass"].ToString(); Type type = Type.GetType(factoryClass); Console.WriteLine("factoryClass ==> " + factoryClass); try { return((IServiceStackAbstractFactory)Activator.CreateInstance(type)); } catch (Exception e) { Console.WriteLine(e.ToString()); return(null); } }
/// <summary> /// Construtor padrao /// </summary> private FaxServerService() { try { faxServer = new FaxServer(); faxServer.ServerName = PropertiesUtil.getInstance().getProperties("rf_host"); faxServer.UseNTAuthentication = PropertiesUtil.getInstance().getProperties("rf_nt_authentication") == "true" ? BoolType.True : BoolType.False; faxServer.AuthorizationUserID = PropertiesUtil.getInstance().getProperties("rf_login"); faxServer.AuthorizationUserPassword = PropertiesUtil.getInstance().getProperties("rf_passwd"); faxServer.Protocol = CommunicationProtocolType.cpTCPIP; ServerInfo serverInfo = faxServer.ServerInfo; } catch (Exception e) { Logger.LOGGER_ERROR("Não foi possível conectar ao servidor RightFax com as configuraçõe informadas: {0}".Replace("{0}", e.Message)); } }
/// <summary> /// Construtor padrao /// </summary> public UserService() { Users users = FaxServerService.getFaxServerIntance().Users; mapUsers = new Dictionary <string, User>(); foreach (User us in users) { if (us.ID.ToUpper().Equals(PropertiesUtil.getInstance().getProperties("rf_user_id").ToUpper())) { origemFaxBox = us; } if (!mapUsers.ContainsKey(us.RoutingCode)) { mapUsers.Add(us.RoutingCode, us); } } }
/// <summary> /// Inicia execucao dos jobs para analise dos faxes recebidos /// e analise do ciclo de vida dos arquivos XML nao processado /// </summary> public void startJobs() { var properties = new NameValueCollection(); properties["quartz.threadPool.threadCount"] = "1"; scheduler = new StdSchedulerFactory(properties).GetScheduler(); var faxJob = new JobDetailImpl("FaxJob", "FaxGroupJob", typeof(FaxJob)); var trigger1 = new CronTriggerImpl("FaxTrigger", "GrupoFaxTrigger", "FaxJob", "FaxGroupJob", PropertiesUtil.getInstance().getProperties("cron_move_fax")); var xmlJob = new JobDetailImpl("XMLJob", "XMLGroupJob", typeof(XMLJob)); var trigger2 = new CronTriggerImpl("XMLTrigger", "GrupoXMLTrigger", "XMLJob", "XMLGroupJob", PropertiesUtil.getInstance().getProperties("cron_xml_move_age")); scheduler.ScheduleJob(faxJob, trigger1); scheduler.ScheduleJob(xmlJob, trigger2); scheduler.Start(); }
/// <summary> /// 扫描Bean特性的方法,并创建实例。 /// </summary> /// <param name="dlls">指定的要被扫描的dll。</param> private void ScanBeanAttribute(string[] dlls) { foreach (string dll in dlls) { Assembly assembly = Assembly.LoadFile(dll); Type[] types = assembly.GetTypes(); foreach (Type clazz in types) { if (clazz.IsClass) { //1.扫描类的Configuration特性 //获取属性 Attribute attributeConfigurationAttribute = clazz.GetCustomAttribute(typeof(ConfigurationAttribute)); if (attributeConfigurationAttribute == null)//如果该类没有Configuration特性 { continue; } ConfigurationAttribute configurationAttribute = (ConfigurationAttribute)attributeConfigurationAttribute; string beanName = clazz.Name.Substring(0, 1).ToLower() + (clazz.Name.Length > 1 ? clazz.Name.Substring(1) : string.Empty); if (!string.IsNullOrWhiteSpace(configurationAttribute.Name)) { beanName = configurationAttribute.Name; } bool isDefault = true;//是否使用默认配置文件 PropertiesUtil _properties = null; string configurationPath = "application.properties"; if (!string.IsNullOrWhiteSpace(configurationAttribute.Path))//如果设置了ConfigurationAttribute的Path值 { configurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configurationAttribute.Path); _properties = new PropertiesUtil(configurationPath); isDefault = false; } //2.扫描字段的Value特性 FieldInfo[] fieldInfos = clazz.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fieldInfos) { Attribute attributeValueAttribute = fieldInfo.GetCustomAttribute(typeof(ValueAttribute)); if (attributeValueAttribute == null)//如果此字段没有Value特性 { continue; } ValueAttribute valueAttribute = (ValueAttribute)attributeValueAttribute; string valueName = fieldInfo.Name; //字段名称 if (!string.IsNullOrWhiteSpace(valueName)) //如果设置了ValueAttribute的Key值 { valueName = valueAttribute.Key; } if (BeanContainer.ContainsKey(beanName)) { if (isDefault == false)//如果使用的不是默认配置文件 { fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(_properties[valueName], fieldInfo.FieldType)); } else { fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(Properties[valueName], fieldInfo.FieldType)); } } } //3.扫描方法的Bean特性 MethodInfo[] methods = clazz.GetMethods(); foreach (MethodInfo method in methods) { Attribute attributeBeanAttribute = method.GetCustomAttribute(typeof(BeanAttribute)); if (attributeBeanAttribute == null)//如果此方法没有Bean特性 { continue; } BeanAttribute beanAttribute = (BeanAttribute)attributeBeanAttribute; string methodName = method.Name; //方法名称 if (!string.IsNullOrWhiteSpace(beanAttribute.Name)) //如果设置了BeanAttribute的Name值 { methodName = beanAttribute.Name; } if ("Void".Equals(method.ReturnType.Name))//如果此方法无返回值 { throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。方法需要返回值。", methodName)); } if (BeanContainer.ContainsKey(beanAttribute.Name))//判断单例容器里是否已存在 { throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。已经存在名为‘{1}’的实例。", methodName, methodName)); } //4.扫描方法参数的Parameter特性 ParameterInfo[] parameterInfos = method.GetParameters(); int parameterCount = parameterInfos.Length; if (parameterCount > 0)//如果有参数 { object[] parameterValues = new object[parameterCount]; int index = 0; foreach (ParameterInfo parameterInfo in parameterInfos)//设置参数的值 { Attribute attributeParameterAttribute = parameterInfo.GetCustomAttribute(typeof(ParameterAttribute)); string parameterName = parameterInfo.Name; //默认参数的名称 if (attributeParameterAttribute != null) //如果有特性标注 { ParameterAttribute parameterAttribute = (ParameterAttribute)attributeParameterAttribute; parameterName = parameterAttribute.Name; } if (!BeanContainer.ContainsKey(parameterName)) //如果从容器中找不到参数的实例 { if (parameterInfo.HasDefaultValue) //根据参数是否设置了默认值来决定是否抛出异常 { parameterValues[index] = parameterInfo.DefaultValue; continue; } throw new BeanNotFoundException(string.Format("找不到指定的实例‘{0}’。", parameterName)); } parameterValues[index] = BeanContainer[parameterName].Bean; index++; } if (BeanContainer.ContainsKey(beanName)) { //执行方法,得到方法的返回值,并存入单例容器 object objReturn = method.Invoke(BeanContainer[beanName].Bean, parameterValues); BeanContainer.Add(methodName, new BeanInfo() { Bean = objReturn, AtrributeType = AtrributeType.Bean }); } } else//如果无参数 { if (BeanContainer.ContainsKey(beanName)) { //执行方法,得到方法的返回值,并存入单例容器 object objReturn = method.Invoke(BeanContainer[beanName].Bean, null); BeanContainer.Add(methodName, new BeanInfo() { Bean = objReturn, AtrributeType = AtrributeType.Bean }); } } } //end : foreach (MethodInfo method in methods) } //end : if (clazz.IsClass) } //end : foreach (Type clazz in types) } //end : foreach (string dll in dlls) }