public void ShowGameGroupJoinMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId) { var result = MockResults.GetGenericResult(int.Parse(callbackId), this.ResultExtras); callback(new ResultContainer(result)); }
protected void Page_Load(object sender, EventArgs e) { Utilities util = new Utilities(); string eid = Convert.ToString(Session["eid"]); int id = Convert.ToInt32(Request.Form["id"]); if (Request.Form["id"] != null) { if (util.checkUsersPic(id, eid) || (int) Session["lvl"] == 3) { int PictureID; string picname, picdesc; picname = Request.Form["picname"]; picdesc = Request.Form["description"]; PictureID = Convert.ToInt32(Request.Form["id"]); this.UpdatePicture(PictureID, picname, picdesc); Response.Redirect("default.aspx?id=" + PictureID); } } else if(!util.checkUsersPic(id, eid)) { Gavan.Global.error = "התמונה איננה שלך."; } else { Response.Redirect("default.aspx"); } }
public bool hasCrop(Utilities.CropTypes crop_in) { if (crops[crop_in].Count != 0) return true; else return false; }
public Blocker(Utilities.Graphics.AnimatedSprite sprite, Shape colShape, bool isAbovePlayer, float maxSpeed = 0.0f, float mass = 1.0f) : base(colShape, Single.PositiveInfinity, maxSpeed) { IsAbovePlayer = isAbovePlayer; Sprite = sprite; Mass = mass; }
public VoicemailScriptProcessor(WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow extension, VoicemailService vmService, PBXRegistrarService registrarService, Utilities.PluginManagement.PluginManager pluginManager) { this.extension = extension; this.vmService = vmService; this.registrarService = registrarService; this.pluginManager = pluginManager; }
private void CurrentObjectives_CollectionChanged(System.Collections.ICollection source, Utilities.Collections.NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { for (int i = 0; i < e.NewItems.Count; i++) { if (_ObjectiveImages.Length < i) return; _ObjectiveImages[i].Texture = Food.GetFoodImage(((FoodObjective)e.NewItems[i]).FoodType).texture; objectif = ((FoodObjective)e.NewItems[i]).FoodType; _ObjectiveImages[i].Show(); ((FoodObjective)e.NewItems[i]).PropertyChanged += ObjectivesUIManager_PropertyChanged; } } else if (e.Action == NotifyCollectionChangedAction.Remove) { for (int i = 0; i < e.OldItems.Count; i++) { ((FoodObjective)e.NewItems[i]).PropertyChanged -= ObjectivesUIManager_PropertyChanged; } } else if (e.Action == NotifyCollectionChangedAction.Reset) { for (int i = 0; i < e.OldItems.Count; i++) { ((FoodObjective)e.NewItems[i]).PropertyChanged -= ObjectivesUIManager_PropertyChanged; } } }
protected void Page_Load(object sender, EventArgs e) { Utilities util = new Utilities(); string eid = Convert.ToString(Session["eid"]); if (!String.IsNullOrEmpty(Request.QueryString["id"])) { int id = Convert.ToInt32(Request.QueryString["id"]); if (existComment(id)) { if (util.checkUsersComment(id, eid) || (int)Session["lvl"] == 3) { deleteComment(id); Response.Redirect("/Pictures/?id=" + Session["PictureID"]); } } else { Gavan.Global.error = "התגובה אינה נמצאה."; } } else { Response.Redirect("../default.aspx"); } }
private void VisitBinaryExpression(Utilities.ContinuationOperator continuation, BinaryExpression binExpr, bool neg) { ExpressionType oper = binExpr.NodeType; ExpressionType[] AndOperators = { ExpressionType.And, ExpressionType.AndAlso }; ExpressionType[] OrOperators = { ExpressionType.Or, ExpressionType.OrElse }; ExpressionType[] binOperators = AndOperators.Concat(OrOperators).ToArray(); if (binOperators.Contains(binExpr.NodeType)) { VisitExpression(continuation, binExpr.Left, neg); if (binOperators.Contains(binExpr.Left.NodeType) & binOperators.Contains(binExpr.Right.NodeType)) { if (AndOperators.Contains(binExpr.NodeType)) _encodedQuery += "NQ"; if (OrOperators.Contains(binExpr.NodeType)) _encodedQuery += "^NQ"; } VisitExpression((Utilities.ContinuationOperator)binExpr.NodeType, binExpr.Right, neg); } else VisitSimpleExpression(continuation, binExpr, neg); }
public EncoreClient() { encoreClient = new Utilities(); encoreInstance = new Instance(); encoreLogDetail = new LogDetail(); encoreLang = new Language(); }
public void size(Utilities.Vec2Int size) { didBackgroundUpdate = true; _background.resize(size); _size = _background.size(); }
public MessageInfo(int msgId, int userId, int userChat, Utilities.Common.TYPE type) { MessageID = msgId; UserID = userId; UserChat = userChat; Type = type; }
public void LoadSideNavigationItems(Utilities.TopLevelNavigation pageParent, string url) { // Create generic list to house side nav items List<BusinessLogic.SideNavigationItem> sideNavItems = new List<BusinessLogic.SideNavigationItem>(); switch (pageParent) { case Utilities.TopLevelNavigation.AboutUs: sideNavItems.Add(new BusinessLogic.SideNavigationItem("navWhoIsOMS", "aboutus.aspx", "Who is OMS", "/about-us", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("navWhereWeServe", "whereweserve.aspx", "Where we Serve", "/where-we-serve", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("navOmsHistory", "#", "OMS History", "/one-mission-society-history", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("navArticlesOfFaith", "articlesoffaith.aspx", "Articles of Faith", "/articles-of-faith", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("BoardOfTrustees", "#", "Board of Trustees", "/board-of-trustees", false, false)); sideNavItems.First(x => x.URL == url || x.SeoAlias == url).IsActive = true; break; case Utilities.TopLevelNavigation.Give: sideNavItems.Add(new BusinessLogic.SideNavigationItem("navGiveToOMS", "Give.aspx", "Give to OMS", "/give", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("navGiveToAProject", "project.aspx", "Give to a Project", "/give/projects", false, false)); sideNavItems.Add(new BusinessLogic.SideNavigationItem("navGiveToAMissionary", "#", "Give to a Missionary", "/give/missionary", false, false)); var activeNode = sideNavItems.FirstOrDefault(x => x.URL == url || x.SeoAlias == url); if (activeNode != null) activeNode.IsActive = true; break; } // Add contextual side item if (this.ContextualSideNavItem != null) { sideNavItems.Add(this.ContextualSideNavItem); } HttpContext.Current.Session.Add("SideNavigationItems", sideNavItems); }
private void SetSizeProfile(Utilities.WAPackIaaS.DataContract.VirtualMachine vm) { vm.CPUCount = VMSizeProfile.CPUCount; vm.Memory = VMSizeProfile.Memory; vm.DynamicMemoryEnabled = VMSizeProfile.DynamicMemoryEnabled; vm.DynamicMemoryMaximumMB = VMSizeProfile.DynamicMemoryMaximumMB; vm.DynamicMemoryMinimumMB = VMSizeProfile.DynamicMemoryMinimumMB; }
public static void createTile(QuadNode<Tile> node, Utilities.Vec2Int pos) { if (_defaultFloorTex == null) _defaultFloorTex = Resources.Load<Texture2D>("Textures/Game Environment/Tile"); Tile tile = new Tile(node, null, pos); tile.setFloorTexture(_defaultFloorTex); }
public void ShowLoginMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId, string permissions) { var result = MockResults.GetLoginResult(int.Parse(callbackId), permissions, this.ResultExtras); callback(new ResultContainer(result)); }
public void ShowLoginMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId, string permsisions) { var dialog = ComponentFactory.GetComponent<MockLoginDialog>(); dialog.Callback = callback; dialog.CallbackID = callbackId; }
protected void DeletePicture(int pictureID) { Utilities util = new Utilities(); string path = util.getFileName(pictureID); File.Delete(Server.MapPath(path)); deleteFromPics(pictureID); delteFromRanks(pictureID); deleteFromComments(pictureID); }
// Input handling method public void OnKeyPressed(object sender, Utilities.KeyEventArgs e) { // Pass key event args to the current game state currentMenu.HandleInput(e); //*// if (e.code == ConsoleKey.Escape) Console.Title = "Stop being a dick"; //*// }
public static void UpdateDb(string trackCode, Utilities.Surface surface) { ParSpeed.DeleteFromDb(trackCode, surface); Dictionary<string, List<double>> times = new Dictionary<string, List<double>>(); foreach (string fullpath in DailyCard.ExistingFiles) { string filename = Path.GetFileName(fullpath); if (filename.Substring(0, trackCode.Length).ToUpper() == trackCode.ToUpper()) { if (null != NotifyObserverEvent) { NotifyObserverEvent(string.Format("Processing File: {0}", filename)); } DailyCard dc = DailyCard.Load(fullpath); foreach (Race race in dc.Races) { if (race.ExistsInDb && surface == race.SurfaceWhereTheRaceWasRun) { RaceClassification rc = race.Classification; if (null != rc && rc.IsValid) { double normalizedSpeed = race.UnadjustedNormalizedSpeedOfTheRace; if (normalizedSpeed > 0.0) { string key = rc.ToString(); if (!times.ContainsKey(key)) { times.Add(key, new List<double>()); } times[key].Add(race.UnadjustedNormalizedSpeedOfTheRace); } } } } } } foreach (KeyValuePair<string, List<double>> pair in times) { double sum = 0.0, count = 0.0; foreach (double d in pair.Value) { sum += d; ++count; } ParSpeed ps = new ParSpeed(pair.Key, sum / count, pair.Value.Count, trackCode,surface); if (null != NotifyObserverEvent) { NotifyObserverEvent(ps.ToString()); } ps.SaveToDb(); } }
void videoHandler_VideoWatchedEvent(Utilities.VideoWatchedEventArgs ev) { if (MainWindow.CurrentMainTabIndex == MainWindow.TAB_MAIN_Playlists) { PlaylistVM pl = this.DataContext as PlaylistVM; if (pl == null) return; pl.PopulatePlaylistObjects(); ShowNextEpisode(); } }
internal ParSpeed( string raceClassification, double avgSpeed, int sampleSize, string trackCode, Utilities.Surface surface) { _raceClassification = raceClassification; _avgSpeed = avgSpeed; _sampleSize = sampleSize; _surface = surface; _trackCode = trackCode; }
public InverseDirectionDLG(IEditProperties2 EditorProperties) { InitializeComponent(); m_ToolTip1 = new System.Windows.Forms.ToolTip(); m_EditorProperties = EditorProperties; Utilities Utils = new Utilities(); string sDesktopVers = Utils.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") sDesktopVers = "Desktop10.1"; else sDesktopVers = "Desktop" + sDesktopVers; string sValues = Utils.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.FabricQualityControl_InverseDirection"); IAngularConverter pAngConv = new AngularConverterClass(); if (m_EditorProperties != null) { esriDirectionUnits pUnits = m_EditorProperties.DirectionUnits; string sAngleUnits = pUnits.ToString(); sAngleUnits = sAngleUnits.Replace("esriDU", ""); sAngleUnits = sAngleUnits.Replace("Minutes", " Minutes "); sAngleUnits = sAngleUnits.Replace("Decimal", "Decimal "); this.lblAngleUnits.Text = sAngleUnits; } if (sValues.Trim() == "") sValues = "False,0.000000,True,True,180,True,0.3,True"; string[] Values = sValues.Split(','); try { string sTxt1 = Values[1]; if (m_EditorProperties != null) { int iPrec = m_EditorProperties.AngularUnitPrecision; pAngConv.SetString(Values[1], esriDirectionType.esriDTNorthAzimuth, esriDirectionUnits.esriDUDecimalDegrees); //registry always stores in DD sTxt1 = pAngConv.GetString(esriDirectionType.esriDTNorthAzimuth, m_EditorProperties.DirectionUnits, m_EditorProperties.AngularUnitPrecision); } this.optManualEnteredDirnOffset.Checked = (Values[0].Trim() == "True"); this.txtDirectionOffset.Text = sTxt1; this.optComputeDirnOffset.Checked = (Values[2].Trim() == "True"); this.chkDirectionDifference.Checked = (Values[3].Trim() == "True"); this.txtDirectionDifference.Text = Values[4]; this.chkSubtendedDistance.Checked = (Values[5].Trim() == "True"); this.txtSubtendedDist.Text = Values[6]; this.chkReportResults.Checked = (Values[7].Trim() == "True"); } catch { } }
internal static SpeedNormalizer GetObject(string trackCode, Utilities.Surface surface) { string key = MakeKey(trackCode, surface); if (_speedNormalizer.ContainsKey(key)) { return _speedNormalizer[key]; } else { return AddSpeedNormalizer(trackCode, surface); } }
public DynamicSprite(Utilities.Vec2Int size) { _size = new Utilities.Vec2Int(1, 1); if (size.x > 1) _size.x = size.x; if (size.y > 1) _size.y = size.y; _sprite = null; _data = new List<Color>(size.x * size.y); for (int i = 0; i < _data.Capacity; i++) _data.Add(default(Color)); }
private void LoadClients() { var utilities = new Utilities(); using (var db = new MSPAccountingContext()) { var clients = db.Client.ToList(); cmbbxClient.ItemsSource = clients; var displayName = utilities.GetPropertyName(() => clients.First().Name); cmbbxClient.DisplayMemberPath = displayName; cmbbxClient.SelectedIndex = 0; } }
public void CreateFloatingText(string text_in, Utilities.TextTypes type_in) { if (type_in == Utilities.TextTypes.Positive) textColor = Color.green; else if (type_in == Utilities.TextTypes.Negative) textColor = Color.red; else if (type_in == Utilities.TextTypes.Dbug) textColor = Color.yellow; text.text = text_in; text.color = textColor; countdown = 2f; }
protected override void OnClick() { IArray LineLyrArr; IArray PolygonLyrArr; IActiveView pActiveView = ArcMap.Document.ActiveView; IMap pMap = pActiveView.FocusMap; Utilities Utils = new Utilities(); if (!Utils.GetFabricSubLayers(pMap, esriCadastralFabricTable.esriCFTLines, out LineLyrArr)) return; if (!Utils.GetFabricSubLayers(pMap, esriCadastralFabricTable.esriCFTParcels, out PolygonLyrArr)) return; IFeatureLayer pFlyr = (IFeatureLayer)LineLyrArr.get_Element(0); IFeatureClass pFabricLinesFC = pFlyr.FeatureClass; pFlyr = (IFeatureLayer)PolygonLyrArr.get_Element(0); IFeatureClass pFabricParcelsFC = pFlyr.FeatureClass; IProjectedCoordinateSystem2 pPCS = null; IGeoDataset pGeoDS = (IGeoDataset)pFabricLinesFC; ISpatialReference pFabricSpatRef = pGeoDS.SpatialReference; double dMetersPerUnit = 1; bool bFabricIsInGCS = !(pFabricSpatRef is IProjectedCoordinateSystem2); if (pFabricSpatRef != null) { if (!bFabricIsInGCS) { pPCS = (IProjectedCoordinateSystem2)pFabricSpatRef; dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit; } } string fileName =""; if (dMetersPerUnit!=1) fileName = AssemblyDirectory + "\\QualityControlLayers\\QA Symbology Feet.lyr"; else fileName = AssemblyDirectory + "\\QualityControlLayers\\QA Symbology Meters.lyr"; bool bIsBefore1022 = false; string sBuild=Utils.GetDesktopBuildNumberFromRegistry(); int iBuildNumber = 0; if (Int32.TryParse(sBuild, out iBuildNumber)) bIsBefore1022 = iBuildNumber<3542; //CR278039 was fixed 10.2.2.3542 AddQALayerToActiveView(pMap, pFabricLinesFC, pFabricParcelsFC, fileName, dMetersPerUnit, bIsBefore1022, bFabricIsInGCS); }
public void C_SendFile(string cfilePath, string sfilePath, ref Utilities.UpdateInfo notify) { /*UpdateInfo[0] = Complate - bool * UpdateInfo[1] = Cancel - bool * UpdateInfo[2] = ProgreeBarFile Max Value - int * UpdateInfo[3] = ProgreeBarFile Value - int */ ThreadPool.QueueUserWorkItem((o) => { Utilities.UpdateInfo uInfo = (Utilities.UpdateInfo)o; FileStream fs = File.OpenRead(cfilePath); byte[] Buffers; Socket Sok = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Buffers = GetCmd(OpCodeProcess.C_SendFile, string.Format("{0};{1}", fs.Length, sfilePath)); Sok.Connect(config.IP, config.PORT); if (Sok.Connected == true) { Sok.Send(Buffers, Buffers.Length, SocketFlags.None); } Sok.Receive(Buffers, SocketFlags.None); if (Buffers[0] != (byte)OpCodeProcess.S_OK) throw new Exception("Server Refuse"); int readed = 0; Buffers = Utilities.Buffers.GetBuffer(); uInfo.SetValue(2, fs.Length); uInfo.SetValue(3, 0); for (int i = 0; i < fs.Length; ) { if ((bool)uInfo.GetValue(0) == true) { fs.Flush(); fs.Close(); fs.Dispose(); uInfo.SetValue(1, true);//Op Canceled Sok.Close(); return; } readed = fs.Read(Buffers, 0, Buffers.Length - 1); Sok.Send(Buffers, readed, SocketFlags.None); i += readed; uInfo.SetValue(3, i);// File progress value } fs.Flush(); fs.Close(); fs.Dispose(); uInfo.SetValue(3, 0);// File progress value uInfo.SetValue(0, true);//Op Complated }, notify); }
private void VisitContainsExpression(Utilities.ContinuationOperator continuation, MethodCallExpression methodCall, bool neg) { EncodedQueryExpression encodedQuery = new EncodedQueryExpression { ContinuationOperator = continuation, IsNegated = neg, Operator = Utilities.RepoExpressionType.IN, EncodedQuery = _encodedQuery, Expression = methodCall }; if (encodedQuery.HasValue) _encodedQuery = encodedQuery.Value; else VisitExpression(continuation, methodCall, neg); }
internal static void DeleteFromDb(string trackCode, Utilities.Surface surface) { string s = ""; if (surface == Utilities.Surface.Turf) { s = "T"; } else { s = "D"; } string sql = string.Format("DELETE AVERAGE_SPEED WHERE TRACK_CODE = '{0}' AND SURFACE = '{1}'", trackCode, s); SqlCommand myCommand = new SqlCommand(sql, Hogar.DbTools.DbUtilities.SqlConnection); myCommand.ExecuteNonQuery(); }
/// <summary> /// Retorna uma instancia do servico correspondente ao tipo /// no endereco fornecido /// </summary> /// <typeparam name="T">Class Type a ser instanciada</typeparam> /// <param name="url">Url completa do Endpoint</param> /// <param name="ativacaolocal">Flag indicando se a ativacao sera local ou remota (via wcf)</param> /// <param name="callbackImpl">objeto que implementa o tratamento de callbacks</param> /// <returns>Nova instancia de T</returns> public static T GetByAddr <T>(string url, bool ativacaolocal = false, object callbackImpl = null) { try { if (callbackImpl != null) { logger.Info("Ativador.GetByAddr<" + typeof(T).ToString() + ">(" + callbackImpl.GetType().ToString() + "," + url + "," + ativacaolocal.ToString() + ")"); } else { logger.Info("Ativador.GetByAddr<" + typeof(T).ToString() + ">(null," + url + "," + ativacaolocal.ToString() + ")"); } // Inicializa T servico = default(T); Type tipo = typeof(T); // ServicoInfo servicoInfo = new ServicoInfo(); // servicoInfo.AtivacaoDefaultTipo = ServicoAtivacaoTipo.WCF; // if (ativacaolocal) // { // servicoInfo.AtivacaoDefaultTipo = ServicoAtivacaoTipo.Local; // } // servicoInfo.AtivarWCF = true; //// servicoInfo. // ServicoEndPointInfo endpoint = new ServicoEndPointInfo(); // endpoint.Endereco = url; // endpoint.NomeBindingType = Utilities.GetBindingType(url); // servicoInfo.N // Primeira tentativa deve ser criação local? if (ativacaolocal) { logger.Debug("Ativando " + tipo.FullName + " localmente"); // Cria o serviço servico = ServicoHostColecao.Default.ReceberServico <T>(); } if (servico == null) { ContractDescription cd; logger.Debug("Ativando " + tipo.FullName + " como WCF"); logger.Debug("Criando Binding para Endpoint: " + url); // Cria via wcf Binding binding = Utilities.GetBinding(url); //(Binding) // typeof(BasicHttpBinding).Assembly.CreateInstance( // servicoInfo.EndPoints[0].NomeBindingType); binding.ReceiveTimeout = new TimeSpan(0, 2, 0); binding.SendTimeout = new TimeSpan(0, 1, 0); binding.OpenTimeout = new TimeSpan(0, 0, 30); binding.CloseTimeout = new TimeSpan(0, 0, 30); string bindtype = Utilities.GetBindingType(url); if (bindtype.Equals("System.ServiceModel.NetTcpBinding")) { ((NetTcpBinding)binding).MaxReceivedMessageSize = 8000000; ((NetTcpBinding)binding).ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; //((NetTcpBinding)binding).Security.Mode = SecurityMode.None; } if (bindtype.Equals("System.ServiceModel.BasicHttpBinding")) { logger.Debug("Binding setado BasicHttpBinding , verificando por callback"); ((BasicHttpBinding)binding).MaxReceivedMessageSize = int.MaxValue; ((BasicHttpBinding)binding).ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; //((NetTcpBinding)binding).Security.Mode = SecurityMode.None; } logger.Debug("Binding criado, verificando por callback"); // Verifica se tem callback // Mesmo que não tenha informado, tem que ver se tem contrato especificado na interface bool temCallback = callbackImpl != null; if (!temCallback) { object[] attrs = typeof(T).GetCustomAttributes(typeof(ServiceContractAttribute), true); if (attrs.Length == 1) { if (((ServiceContractAttribute)attrs[0]).CallbackContract != null) { temCallback = true; } } } // Cria dependendo se tem contrato ou não if (!temCallback) { logger.Debug("Servico " + tipo.FullName + " nao tem callback, criando channel "); IChannelFactory <T> canal = new ChannelFactory <T>(binding); canal.Faulted += new EventHandler(_channelFaulted); servico = canal.CreateChannel(new EndpointAddress(url)); cd = ((ChannelFactory)canal).Endpoint.Contract; } else { logger.Debug("Servico " + tipo.FullName + " tem callback, criando channel duplex"); DuplexChannelFactory <T> canal = null; if (callbackImpl == null) { logger.Error("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback."); throw new Exception("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback."); } canal = new DuplexChannelFactory <T>(callbackImpl, binding); canal.Faulted += new EventHandler(_channelFaulted); servico = canal.CreateChannel(new EndpointAddress(url)); cd = canal.Endpoint.Contract; //IServicoComCallback servicoComCallback = servico as IServicoComCallback; //if (servicoComCallback != null) // servicoComCallback.Registrar(parametros); } if (cd != null) { foreach (OperationDescription od in cd.Operations) { DataContractSerializerOperationBehavior serializerBh = od.Behaviors.Find <DataContractSerializerOperationBehavior>(); if (serializerBh == null) { logger.Info("Adicionando DataContractSerializerOperationBehavior"); serializerBh = new DataContractSerializerOperationBehavior(od); od.Behaviors.Add(serializerBh); } logger.Info("Setando MaxItemsInObjectGraph para operacao: " + od.Name); serializerBh.MaxItemsInObjectGraph = 8000000; } } ((IContextChannel)servico).OperationTimeout = new TimeSpan(0, 10, 0); } if (servico == null) { string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n"; msg += "Verifique se existe <servicoinfo> nas configuracoes locais,\n"; msg += "ou se o mesmo foi registrado no ServicoLocalizador e seu hoster esta ativo."; logger.Error("ERRO: SERVICO [" + tipo.FullName + "] NAO FOI ATIVADO!!!"); throw new Exception(msg); } // Retorna return(servico); } catch (Exception ex) { logger.Error("Erro em Ativador.Get(" + typeof(T).FullName + ")", ex); throw ex; } }
/** * Azure Compute sample for managing virtual machine scale sets - * - Create a virtual machine scale set behind an Internet facing load balancer * - Install Apache Web servers in virtual machines in the virtual machine scale set * - Stop a virtual machine scale set * - Start a virtual machine scale set * - Update a virtual machine scale set * - Double the no. of virtual machines * - Restart a virtual machine scale set */ public static void RunSample(IAzure azure) { string vmssName = SdkContext.RandomResourceName("vmss", 24); string storageAccountName1 = SdkContext.RandomResourceName("stg1", 24); string storageAccountName2 = SdkContext.RandomResourceName("stg2", 24); string storageAccountName3 = SdkContext.RandomResourceName("stg3", 24); string rgName = SdkContext.RandomResourceName("rgCOVS", 15); string vnetName = SdkContext.RandomResourceName("vnet", 24); string loadBalancerName1 = SdkContext.RandomResourceName("intlb" + "-", 18); string publicIpName = "pip-" + loadBalancerName1; string frontendName = loadBalancerName1 + "-FE1"; string backendPoolName1 = loadBalancerName1 + "-BAP1"; string backendPoolName2 = loadBalancerName1 + "-BAP2"; try { //============================================================= // Create a virtual network with a frontend subnet Utilities.Log("Creating virtual network with a frontend subnet ..."); var network = azure.Networks.Define(vnetName) .WithRegion(Region.USEast) .WithNewResourceGroup(rgName) .WithAddressSpace("172.16.0.0/16") .DefineSubnet("Front-end") .WithAddressPrefix("172.16.1.0/24") .Attach() .Create(); Utilities.Log("Created a virtual network"); // Print the virtual network details Utilities.PrintVirtualNetwork(network); //============================================================= // Create a public IP address Utilities.Log("Creating a public IP address..."); var publicIpAddress = azure.PublicIPAddresses.Define(publicIpName) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .WithLeafDomainLabel(publicIpName) .Create(); Utilities.Log("Created a public IP address"); // Print the IPAddress details Utilities.PrintIPAddress(publicIpAddress); //============================================================= // Create an Internet facing load balancer with // One frontend IP address // Two backend address pools which contain network interfaces for the virtual // machines to receive HTTP and HTTPS network traffic from the load balancer // Two load balancing rules for HTTP and HTTPS to map public ports on the load // balancer to ports in the backend address pool // Two probes which contain HTTP and HTTPS health probes used to check availability // of virtual machines in the backend address pool // Three inbound NAT rules which contain rules that map a public port on the load // balancer to a port for a specific virtual machine in the backend address pool // - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23 Utilities.Log("Creating a Internet facing load balancer with ..."); Utilities.Log("- A frontend IP address"); Utilities.Log("- Two backend address pools which contain network interfaces for the virtual\n" + " machines to receive HTTP and HTTPS network traffic from the load balancer"); Utilities.Log("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" + " balancer to ports in the backend address pool"); Utilities.Log("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" + " of virtual machines in the backend address pool"); Utilities.Log("- Two inbound NAT rules which contain rules that map a public port on the load\n" + " balancer to a port for a specific virtual machine in the backend address pool\n" + " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23"); var loadBalancer1 = azure.LoadBalancers.Define(loadBalancerName1) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .DefinePublicFrontend(frontendName) .WithExistingPublicIPAddress(publicIpAddress) .Attach() // Add two backend one per rule .DefineBackend(backendPoolName1) .Attach() .DefineBackend(backendPoolName2) .Attach() // Add two probes one per rule .DefineHttpProbe(httpProbe) .WithRequestPath("/") .WithPort(80) .Attach() .DefineHttpProbe(httpsProbe) .WithRequestPath("/") .WithPort(443) .Attach() // Add two rules that uses above backend and probe .DefineLoadBalancingRule(httpLoadBalancingRule) .WithProtocol(TransportProtocol.Tcp) .WithFrontend(frontendName) .WithFrontendPort(80) .WithProbe(httpProbe) .WithBackend(backendPoolName1) .Attach() .DefineLoadBalancingRule(httpsLoadBalancingRule) .WithProtocol(TransportProtocol.Tcp) .WithFrontend(frontendName) .WithFrontendPort(443) .WithProbe(httpsProbe) .WithBackend(backendPoolName2) .Attach() // Add nat pools to enable direct VM connectivity for // SSH to port 22 and TELNET to port 23 .DefineInboundNatPool(natPool50XXto22) .WithProtocol(TransportProtocol.Tcp) .WithFrontend(frontendName) .WithFrontendPortRange(5000, 5099) .WithBackendPort(22) .Attach() .DefineInboundNatPool(natPool60XXto23) .WithProtocol(TransportProtocol.Tcp) .WithFrontend(frontendName) .WithFrontendPortRange(6000, 6099) .WithBackendPort(23) .Attach() .Create(); // Print load balancer details Utilities.Log("Created a load balancer"); Utilities.PrintLoadBalancer(loadBalancer1); //============================================================= // Create a virtual machine scale set with three virtual machines // And, install Apache Web servers on them Utilities.Log("Creating virtual machine scale set with three virtual machines" + " in the frontend subnet ..."); var t1 = DateTime.UtcNow; var fileUris = new List <string>(); fileUris.Add(apacheInstallScript); var virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmssName) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .WithSku(VirtualMachineScaleSetSkuTypes.StandardD3v2) .WithExistingPrimaryNetworkSubnet(network, "Front-end") .WithExistingPrimaryInternetFacingLoadBalancer(loadBalancer1) .WithPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2) .WithPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(userName) .WithSsh(sshKey) .WithNewStorageAccount(storageAccountName1) .WithNewStorageAccount(storageAccountName2) .WithNewStorageAccount(storageAccountName3) .WithCapacity(3) // Use a VM extension to install Apache Web servers .DefineNewExtension("CustomScriptForLinux") .WithPublisher("Microsoft.OSTCExtensions") .WithType("CustomScriptForLinux") .WithVersion("1.4") .WithMinorVersionAutoUpgrade() .WithPublicSetting("fileUris", fileUris) .WithPublicSetting("commandToExecute", installCommand) .Attach() .Create(); var t2 = DateTime.UtcNow; Utilities.Log("Created a virtual machine scale set with " + "3 Linux VMs & Apache Web servers on them: (took " + ((t2 - t1).TotalSeconds) + " seconds) \r\n"); // Print virtual machine scale set details // Utilities.Print(virtualMachineScaleSet); //============================================================= // Stop the virtual machine scale set Utilities.Log("Stopping virtual machine scale set ..."); virtualMachineScaleSet.PowerOff(); Utilities.Log("Stopped virtual machine scale set"); //============================================================= // Start the virtual machine scale set Utilities.Log("Starting virtual machine scale set ..."); virtualMachineScaleSet.Start(); Utilities.Log("Started virtual machine scale set"); //============================================================= // Update the virtual machine scale set // - double the no. of virtual machines Utilities.Log("Updating virtual machine scale set " + "- double the no. of virtual machines ..."); virtualMachineScaleSet.Update() .WithCapacity(6) .Apply(); Utilities.Log("Doubled the no. of virtual machines in " + "the virtual machine scale set"); //============================================================= // re-start virtual machine scale set Utilities.Log("re-starting virtual machine scale set ..."); virtualMachineScaleSet.Restart(); Utilities.Log("re-started virtual machine scale set"); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
/// <summary> /// Renders the layer /// </summary> /// <param name="graphics">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics graphics, MapViewport map) { if (!map.Size.IsEmpty && map.Size.Width > 0 && map.Size.Height > 0) { var bmp = new Bitmap(map.Size.Width, map.Size.Height, PixelFormat.Format32bppArgb); float resolution = 120; if (this.Resolution != null) { resolution = (float)this.Resolution; } bmp.SetResolution(resolution, resolution); using (var g = Graphics.FromImage(bmp)) { g.InterpolationMode = InterpolationMode; g.Transform = graphics.Transform.Clone(); var extent = new Extent(map.Envelope.MinX, map.Envelope.MinY, map.Envelope.MaxX, map.Envelope.MaxY); var level = Utilities.GetNearestLevel(_source.Schema.Resolutions, map.PixelSize); var tiles = new List <TileInfo>(_source.Schema.GetTileInfos(extent, level)); var tileWidth = _source.Schema.GetTileWidth(level); var tileHeight = _source.Schema.GetTileWidth(level); IList <WaitHandle> waitHandles = new List <WaitHandle>(); var toRender = new ConcurrentDictionary <TileIndex, Bitmap>(); var takenFromCache = new ConcurrentDictionary <TileIndex, bool>(); foreach (TileInfo info in tiles) { var image = _bitmaps.Find(info.Index); if (image != null) { toRender.TryAdd(info.Index, image); takenFromCache.TryAdd(info.Index, true); continue; } if (_fileCache != null && _fileCache.Exists(info.Index)) { var tileBitmap = GetImageFromFileCache(info) as Bitmap; _bitmaps.Add(info.Index, tileBitmap); toRender.TryAdd(info.Index, tileBitmap); takenFromCache.TryAdd(info.Index, true); continue; } var waitHandle = new AutoResetEvent(false); waitHandles.Add(waitHandle); ThreadPool.QueueUserWorkItem(GetTileOnThread, new object[] { _source, info, toRender, waitHandle, true, takenFromCache }); } foreach (var handle in waitHandles) { handle.WaitOne(); } using (var ia = new ImageAttributes()) { if (!_transparentColor.IsEmpty) { ia.SetColorKey(_transparentColor, _transparentColor); } #if !PocketPC ia.SetWrapMode(WrapMode.TileFlipXY); #endif foreach (var info in tiles) { if (!toRender.ContainsKey(info.Index)) { continue; } var bitmap = toRender[info.Index];//_bitmaps.Find(info.Index); if (bitmap == null) { continue; } bitmap.SetResolution(resolution, resolution); var min = map.WorldToImage(new Coordinate(info.Extent.MinX, info.Extent.MinY)); var max = map.WorldToImage(new Coordinate(info.Extent.MaxX, info.Extent.MaxY)); min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y)); max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y)); try { g.DrawImage(bitmap, new Rectangle((int)min.X, (int)max.Y, (int)(max.X - min.X), (int)(min.Y - max.Y)), 0, 0, tileWidth, tileHeight, GraphicsUnit.Pixel, ia); } catch (Exception ee) { Logger.Error(ee.Message); } } } //Add rendered tiles to cache foreach (var kvp in toRender) { if (takenFromCache.ContainsKey(kvp.Key) && !takenFromCache[kvp.Key]) { _bitmaps.Add(kvp.Key, kvp.Value); } } graphics.Transform = new Matrix(); graphics.DrawImageUnscaled(bmp, 0, 0); graphics.Transform = g.Transform; } } }
public ImportText() { InitializeComponent(); Text = Configuration.Settings.Language.ImportText.Title; groupBoxImportText.Text = Configuration.Settings.Language.ImportText.Title; buttonOpenText.Text = Configuration.Settings.Language.ImportText.OpenTextFile; groupBoxImportOptions.Text = Configuration.Settings.Language.ImportText.ImportOptions; groupBoxSplitting.Text = Configuration.Settings.Language.ImportText.Splitting; radioButtonAutoSplit.Text = Configuration.Settings.Language.ImportText.AutoSplitText; radioButtonLineMode.Text = Configuration.Settings.Language.ImportText.OneLineIsOneSubtitle; labelLineBreak.Left = radioButtonLineMode.Left + radioButtonLineMode.Width + 10; labelLineBreak.Text = Configuration.Settings.Language.ImportText.LineBreak; columnHeaderFName.Text = Configuration.Settings.Language.JoinSubtitles.FileName; columnHeaderSize.Text = Configuration.Settings.Language.General.Size; comboBoxLineBreak.Left = labelLineBreak.Left + labelLineBreak.Width + 3; comboBoxLineBreak.Width = groupBoxSplitting.Width - comboBoxLineBreak.Left - 5; checkBoxMultipleFiles.AutoSize = true; checkBoxMultipleFiles.Left = buttonOpenText.Left - checkBoxMultipleFiles.Width - 9; checkBoxMultipleFiles.Text = Configuration.Settings.Language.ImportText.OneSubtitleIsOneFile; listViewInputFiles.Visible = false; radioButtonSplitAtBlankLines.Text = Configuration.Settings.Language.ImportText.SplitAtBlankLines; checkBoxMergeShortLines.Text = Configuration.Settings.Language.ImportText.MergeShortLines; checkBoxRemoveEmptyLines.Text = Configuration.Settings.Language.ImportText.RemoveEmptyLines; checkBoxRemoveLinesWithoutLetters.Text = Configuration.Settings.Language.ImportText.RemoveLinesWithoutLetters; checkBoxGenerateTimeCodes.Text = Configuration.Settings.Language.ImportText.GenerateTimeCodes; checkBoxAutoBreak.Text = Configuration.Settings.Language.Settings.MainTextBoxAutoBreak; labelGapBetweenSubtitles.Text = Configuration.Settings.Language.ImportText.GapBetweenSubtitles; numericUpDownGapBetweenLines.Left = labelGapBetweenSubtitles.Left + labelGapBetweenSubtitles.Width + 3; groupBoxDuration.Text = Configuration.Settings.Language.General.Duration; radioButtonDurationAuto.Text = Configuration.Settings.Language.ImportText.Auto; radioButtonDurationFixed.Text = Configuration.Settings.Language.ImportText.Fixed; buttonRefresh.Text = Configuration.Settings.Language.ImportText.Refresh; groupBoxTimeCodes.Text = Configuration.Settings.Language.ImportText.TimeCodes; groupBoxImportResult.Text = Configuration.Settings.Language.General.Preview; buttonOK.Text = Configuration.Settings.Language.General.Ok; buttonCancel.Text = Configuration.Settings.Language.General.Cancel; SubtitleListview1.InitializeLanguage(Configuration.Settings.Language.General, Configuration.Settings); Utilities.InitializeSubtitleFont(SubtitleListview1); SubtitleListview1.AutoSizeAllColumns(this); if (string.IsNullOrEmpty(Configuration.Settings.Tools.ImportTextSplitting)) { radioButtonAutoSplit.Checked = true; } else if (Configuration.Settings.Tools.ImportTextSplitting.Equals("blank lines", StringComparison.OrdinalIgnoreCase)) { radioButtonSplitAtBlankLines.Checked = true; } else if (Configuration.Settings.Tools.ImportTextSplitting.Equals("line", StringComparison.OrdinalIgnoreCase)) { radioButtonLineMode.Checked = true; } checkBoxMergeShortLines.Checked = Configuration.Settings.Tools.ImportTextMergeShortLines; comboBoxLineBreak.Text = Configuration.Settings.Tools.ImportTextLineBreak; numericUpDownDurationFixed.Enabled = radioButtonDurationFixed.Checked; Utilities.FixLargeFonts(this, buttonOK); _refreshTimer.Interval = 400; _refreshTimer.Tick += RefreshTimerTick; }
void RenderBuffers(DeviceContext deviceContext) { deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <VertexType>(), 0)); deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, SharpDX.DXGI.Format.R32_UInt, 0); deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; }
public override string ToText(Subtitle subtitle, string title) { Errors = null; var ss = Configuration.Settings.SubtitleSettings; if (!string.IsNullOrEmpty(ss.CurrentDCinemaEditRate)) { string[] temp = ss.CurrentDCinemaEditRate.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); double d1, d2; if (temp.Length == 2 && double.TryParse(temp[0], out d1) && double.TryParse(temp[1], out d2)) { _frameRate = d1 / d2; } } string xmlStructure = "<dcst:SubtitleReel xmlns:dcst=\"http://www.smpte-ra.org/schemas/428-7/2007/DCST\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine + " <dcst:Id>urn:uuid:7be835a3-cfb4-43d0-bb4b-f0b4c95e962e</dcst:Id>" + Environment.NewLine + " <dcst:ContentTitleText></dcst:ContentTitleText> " + Environment.NewLine + " <dcst:AnnotationText>This is a subtitle file</dcst:AnnotationText>" + Environment.NewLine + " <dcst:IssueDate>2012-06-26T12:33:59.000-00:00</dcst:IssueDate>" + Environment.NewLine + " <dcst:ReelNumber>1</dcst:ReelNumber>" + Environment.NewLine + " <dcst:Language>en</dcst:Language>" + Environment.NewLine + " <dcst:EditRate>25 1</dcst:EditRate>" + Environment.NewLine + " <dcst:TimeCodeRate>25</dcst:TimeCodeRate>" + Environment.NewLine + " <dcst:StartTime>00:00:00:00</dcst:StartTime> " + Environment.NewLine + " <dcst:LoadFont ID=\"theFontId\">urn:uuid:3dec6dc0-39d0-498d-97d0-928d2eb78391</dcst:LoadFont>" + Environment.NewLine + " <dcst:SubtitleList>" + Environment.NewLine + " <dcst:Font ID=\"theFontId\" Size=\"39\" Weight=\"normal\" Color=\"FFFFFFFF\" Effect=\"border\" EffectColor=\"FF000000\">" + Environment.NewLine + " </dcst:Font>" + Environment.NewLine + " </dcst:SubtitleList>" + Environment.NewLine + "</dcst:SubtitleReel>"; var xml = new XmlDocument(); xml.LoadXml(xmlStructure); xml.PreserveWhitespace = true; var nsmgr = new XmlNamespaceManager(xml.NameTable); nsmgr.AddNamespace("dcst", xml.DocumentElement.NamespaceURI); if (string.IsNullOrEmpty(ss.CurrentDCinemaMovieTitle)) { ss.CurrentDCinemaMovieTitle = title; } if (ss.CurrentDCinemaFontSize == 0 || string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { Configuration.Settings.SubtitleSettings.InitializeDCinameSettings(true); } xml.DocumentElement.SelectSingleNode("dcst:ContentTitleText", nsmgr).InnerText = ss.CurrentDCinemaMovieTitle; if (string.IsNullOrEmpty(ss.CurrentDCinemaSubtitleId) || !ss.CurrentDCinemaSubtitleId.StartsWith("urn:uuid:")) { ss.CurrentDCinemaSubtitleId = "urn:uuid:" + Guid.NewGuid(); } xml.DocumentElement.SelectSingleNode("dcst:Id", nsmgr).InnerText = ss.CurrentDCinemaSubtitleId; xml.DocumentElement.SelectSingleNode("dcst:ReelNumber", nsmgr).InnerText = ss.CurrentDCinemaReelNumber; xml.DocumentElement.SelectSingleNode("dcst:IssueDate", nsmgr).InnerText = ss.CurrentDCinemaIssueDate; if (string.IsNullOrEmpty(ss.CurrentDCinemaLanguage)) { ss.CurrentDCinemaLanguage = "en"; } xml.DocumentElement.SelectSingleNode("dcst:Language", nsmgr).InnerText = ss.CurrentDCinemaLanguage; if (ss.CurrentDCinemaEditRate == null && ss.CurrentDCinemaTimeCodeRate == null) { if (Configuration.Settings.General.CurrentFrameRate == 24) { ss.CurrentDCinemaEditRate = "24 1"; ss.CurrentDCinemaTimeCodeRate = "24"; } else { ss.CurrentDCinemaEditRate = "25 1"; ss.CurrentDCinemaTimeCodeRate = "25"; } } xml.DocumentElement.SelectSingleNode("dcst:EditRate", nsmgr).InnerText = ss.CurrentDCinemaEditRate; xml.DocumentElement.SelectSingleNode("dcst:TimeCodeRate", nsmgr).InnerText = ss.CurrentDCinemaTimeCodeRate; if (string.IsNullOrEmpty(ss.CurrentDCinemaStartTime)) { ss.CurrentDCinemaStartTime = "00:00:00:00"; } xml.DocumentElement.SelectSingleNode("dcst:StartTime", nsmgr).InnerText = ss.CurrentDCinemaStartTime; xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).InnerText = ss.CurrentDCinemaFontUri; int fontSize = ss.CurrentDCinemaFontSize; string loadedFontId = "Font1"; if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontId)) { loadedFontId = ss.CurrentDCinemaFontId; } xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).Attributes["ID"].Value = loadedFontId; xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Size"].Value = fontSize.ToString(); xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Color"].Value = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontColor).TrimStart('#').ToUpper(); xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["ID"].Value = loadedFontId; xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Effect"].Value = ss.CurrentDCinemaFontEffect; xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["EffectColor"].Value = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontEffectColor).TrimStart('#').ToUpper(); XmlNode mainListFont = xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr); int no = 0; foreach (Paragraph p in subtitle.Paragraphs) { if (p.Text != null) { XmlNode subNode = xml.CreateElement("dcst:Subtitle", "dcst"); XmlAttribute id = xml.CreateAttribute("SpotNumber"); id.InnerText = (no + 1).ToString(); subNode.Attributes.Append(id); XmlAttribute fadeUpTime = xml.CreateAttribute("FadeUpTime"); fadeUpTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString(); subNode.Attributes.Append(fadeUpTime); XmlAttribute fadeDownTime = xml.CreateAttribute("FadeDownTime"); fadeDownTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString(); subNode.Attributes.Append(fadeDownTime); XmlAttribute start = xml.CreateAttribute("TimeIn"); start.InnerText = ConvertToTimeString(p.StartTime); subNode.Attributes.Append(start); XmlAttribute end = xml.CreateAttribute("TimeOut"); end.InnerText = ConvertToTimeString(p.EndTime); subNode.Attributes.Append(end); bool alignLeft = p.Text.StartsWith("{\\a1}") || p.Text.StartsWith("{\\a5}") || p.Text.StartsWith("{\\a9}") || // sub station alpha p.Text.StartsWith("{\\an1}") || p.Text.StartsWith("{\\an4}") || p.Text.StartsWith("{\\an7}"); // advanced sub station alpha bool alignRight = p.Text.StartsWith("{\\a3}") || p.Text.StartsWith("{\\a7}") || p.Text.StartsWith("{\\a11}") || // sub station alpha p.Text.StartsWith("{\\an3}") || p.Text.StartsWith("{\\an6}") || p.Text.StartsWith("{\\an9}"); // advanced sub station alpha bool alignVTop = p.Text.StartsWith("{\\a5}") || p.Text.StartsWith("{\\a6}") || p.Text.StartsWith("{\\a7}") || // sub station alpha p.Text.StartsWith("{\\an7}") || p.Text.StartsWith("{\\an8}") || p.Text.StartsWith("{\\an9}"); // advanced sub station alpha bool alignVCenter = p.Text.StartsWith("{\\a9}") || p.Text.StartsWith("{\\a10}") || p.Text.StartsWith("{\\a11}") || // sub station alpha p.Text.StartsWith("{\\an4}") || p.Text.StartsWith("{\\an5}") || p.Text.StartsWith("{\\an6}"); // advanced sub station alpha // remove styles for display text (except italic) string text = RemoveSubStationAlphaFormatting(p.Text); var lines = text.SplitToLines(); int vPos = 1 + lines.Length * 7; int vPosFactor = (int)Math.Round(fontSize / 7.4); if (alignVTop) { vPos = Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8 } else if (alignVCenter) { vPos = (int)Math.Round((lines.Length * vPosFactor * -1) / 2.0); } else { vPos = (lines.Length * vPosFactor) - vPosFactor + Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8 } bool isItalic = false; int fontNo = 0; Stack <string> fontColors = new Stack <string>(); foreach (string line in lines) { XmlNode textNode = xml.CreateElement("dcst:Text", "dcst"); XmlAttribute vPosition = xml.CreateAttribute("Vposition"); vPosition.InnerText = vPos.ToString(); textNode.Attributes.Append(vPosition); XmlAttribute vAlign = xml.CreateAttribute("Valign"); if (alignVTop) { vAlign.InnerText = "top"; } else if (alignVCenter) { vAlign.InnerText = "center"; } else { vAlign.InnerText = "bottom"; } textNode.Attributes.Append(vAlign); textNode.Attributes.Append(vAlign); XmlAttribute hAlign = xml.CreateAttribute("Halign"); if (alignLeft) { hAlign.InnerText = "left"; } else if (alignRight) { hAlign.InnerText = "right"; } else { hAlign.InnerText = "center"; } textNode.Attributes.Append(hAlign); XmlAttribute direction = xml.CreateAttribute("Direction"); direction.InnerText = "ltr"; textNode.Attributes.Append(direction); int i = 0; var txt = new StringBuilder(); var html = new StringBuilder(); XmlNode nodeTemp = xml.CreateElement("temp"); while (i < line.Length) { if (!isItalic && line.Substring(i).StartsWith("<i>")) { if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); txt = new StringBuilder(); } isItalic = true; i += 2; } else if (isItalic && line.Substring(i).StartsWith("</i>")) { if (txt.Length > 0) { XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst"); XmlAttribute italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); if (line.Length > i + 5 && line.Substring(i + 4).StartsWith("</font>")) { XmlAttribute fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Pop(); fontNode.Attributes.Append(fontColor); fontNo--; i += 7; } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); txt = new StringBuilder(); } isItalic = false; i += 3; } else if (line.Substring(i).StartsWith("<font color=") && line.Substring(i + 3).Contains('>')) { int endOfFont = line.IndexOf('>', i); if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); txt = new StringBuilder(); } string c = line.Substring(i + 12, endOfFont - (i + 12)); c = c.Trim('"').Trim('\'').Trim(); if (c.StartsWith('#')) { c = c.TrimStart('#').ToUpper().PadLeft(8, 'F'); } fontColors.Push(c); fontNo++; i += endOfFont - i; } else if (fontNo > 0 && line.Substring(i).StartsWith("</font>")) { if (txt.Length > 0) { XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst"); XmlAttribute fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Pop(); fontNode.Attributes.Append(fontColor); if (line.Length > i + 9 && line.Substring(i + 7).StartsWith("</i>")) { XmlAttribute italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); isItalic = false; i += 4; } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); txt = new StringBuilder(); } fontNo--; i += 6; } else { txt.Append(line[i]); } i++; } if (fontNo > 0) { if (txt.Length > 0) { XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst"); XmlAttribute fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Peek(); fontNode.Attributes.Append(fontColor); if (isItalic) { XmlAttribute italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); } else if (html.Length > 0 && html.ToString().StartsWith("<dcst:Font ")) { XmlDocument temp = new XmlDocument(); temp.LoadXml("<root>" + html.ToString().Replace("dcst:Font", "Font") + "</root>"); XmlNode fontNode = xml.CreateElement("dcst:Font"); fontNode.InnerXml = temp.DocumentElement.SelectSingleNode("Font").InnerXml; foreach (XmlAttribute a in temp.DocumentElement.SelectSingleNode("Font").Attributes) { XmlAttribute newA = xml.CreateAttribute(a.Name); newA.InnerText = a.InnerText; fontNode.Attributes.Append(newA); } XmlAttribute fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Peek(); fontNode.Attributes.Append(fontColor); html = new StringBuilder(); html.Append(fontNode.OuterXml); } } else if (isItalic) { if (txt.Length > 0) { XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst"); XmlAttribute italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); fontNode.InnerText = HtmlUtil.RemoveHtmlTags(line); html.Append(fontNode.OuterXml); } } else { if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); } } textNode.InnerXml = html.ToString(); subNode.AppendChild(textNode); if (alignVTop) { vPos += vPosFactor; } else { vPos -= vPosFactor; } } if (subNode.InnerXml.Length == 0) { // Empty text is just one space XmlNode textNode = xml.CreateElement("dcst:Text", "dcst"); textNode.InnerXml = " "; subNode.AppendChild(textNode); XmlAttribute vPosition = xml.CreateAttribute("Vposition"); vPosition.InnerText = vPos.ToString(); textNode.Attributes.Append(vPosition); XmlAttribute vAlign = xml.CreateAttribute("Valign"); vAlign.InnerText = "bottom"; textNode.Attributes.Append(vAlign); } mainListFont.AppendChild(subNode); no++; } } string result = ToUtf8XmlString(xml).Replace("encoding=\"utf-8\"", "encoding=\"UTF-8\"").Replace(" xmlns:dcst=\"dcst\"", string.Empty); const string res = "Nikse.SubtitleEdit.Resources.SMPTE-428-7-2007-DCST.xsd.gz"; System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); Stream strm = asm.GetManifestResourceStream(res); if (strm != null) { try { var xmld = new XmlDocument(); var rdr = new StreamReader(strm); var zip = new GZipStream(rdr.BaseStream, CompressionMode.Decompress); xmld.LoadXml(result); using (var xr = XmlReader.Create(zip)) { xmld.Schemas.Add(null, xr); xmld.Validate(ValidationCallBack); } } catch (Exception exception) { Errors = "Error validating xml via SMPTE - 428 - 7 - 2007 - DCST.xsd: " + exception.Message; } } return(result); }
private static bool CanMakeThreeLiner(out string text, string input) { text = string.Empty; if (input.Length < Configuration.Settings.General.SubtitleLineMaximumLength * 3 && input.Length > Configuration.Settings.General.SubtitleLineMaximumLength * 1.5) { var breaked = Utilities.AutoBreakLine(input).SplitToLines(); if (breaked.Length == 2 && (breaked[0].Length > Configuration.Settings.General.SubtitleLineMaximumLength || breaked[1].Length > Configuration.Settings.General.SubtitleLineMaximumLength)) { var first = new StringBuilder(); var second = new StringBuilder(); var third = new StringBuilder(); foreach (string word in input.Replace(Environment.NewLine, " ").Replace(" ", " ").Split(' ')) { if (first.Length + word.Length < Configuration.Settings.General.SubtitleLineMaximumLength) { first.Append(' '); first.Append(word); } else if (second.Length + word.Length < Configuration.Settings.General.SubtitleLineMaximumLength) { second.Append(' '); second.Append(word); } else { third.Append(' '); third.Append(word); } } if (first.Length <= Configuration.Settings.General.SubtitleLineMaximumLength && second.Length <= Configuration.Settings.General.SubtitleLineMaximumLength && third.Length <= Configuration.Settings.General.SubtitleLineMaximumLength && third.Length > 10) { if (second.Length > 15) { string ending = second.ToString().Substring(second.Length - 9); int splitPos = -1; if (ending.Contains(". ")) { splitPos = ending.IndexOf(". ", StringComparison.Ordinal) + second.Length - 9; } else if (ending.Contains("! ")) { splitPos = ending.IndexOf("! ", StringComparison.Ordinal) + second.Length - 9; } else if (ending.Contains(", ")) { splitPos = ending.IndexOf(", ", StringComparison.Ordinal) + second.Length - 9; } else if (ending.Contains("? ")) { splitPos = ending.IndexOf("? ", StringComparison.Ordinal) + second.Length - 9; } if (splitPos > 0) { text = Utilities.AutoBreakLine(first.ToString().Trim() + second.ToString().Substring(0, splitPos + 1)).Trim() + Environment.NewLine + (second.ToString().Substring(splitPos + 1) + third).Trim(); return(true); } } text = first + Environment.NewLine + second + Environment.NewLine + third; return(true); } } } return(false); }
public static IWebHost BuildWebHost(IPEndPoint CovenantEndpoint, string CovenantUri, string CovenantUsername, string CovenantPassword) => new WebHostBuilder() .UseKestrel(options => { options.Listen(CovenantEndpoint, listenOptions => { listenOptions.UseHttps(httpsOptions => { if (!File.Exists(Common.CovenantPrivateCertFile) || !File.Exists(Common.CovenantPublicCertFile)) { Console.WriteLine("Creating cert..."); X509Certificate2 certificate = Utilities.CreateSelfSignedCertificate(CovenantEndpoint.Address, "CN=Covenant"); File.WriteAllBytes(Common.CovenantPrivateCertFile, certificate.Export(X509ContentType.Pfx, CovenantPassword)); File.WriteAllBytes(Common.CovenantPublicCertFile, certificate.Export(X509ContentType.Cert)); } try { httpsOptions.ServerCertificate = new X509Certificate2(Common.CovenantPrivateCertFile, CovenantPassword); } catch (CryptographicException) { Console.Error.WriteLine("Error importing Covenant certificate. Wrong password? Must use initial user/password."); } httpsOptions.SslProtocols = SslProtocols.Tls12; Console.WriteLine("Using Covenant certificate with hash: " + httpsOptions.ServerCertificate.GetCertHashString()); }); }); }) .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { string appsettingscontents = File.ReadAllText(Common.CovenantAppSettingsFile); if (appsettingscontents.Contains(Common.CovenantJwtKeyReplaceMessage)) { Console.WriteLine("Found default JwtKey, replacing with auto-generated key..."); File.WriteAllText(Common.CovenantAppSettingsFile, appsettingscontents.Replace(Common.CovenantJwtKeyReplaceMessage, Utilities.GenerateJwtKey())); } var env = hostingContext.HostingEnvironment; config.AddJsonFile(Common.CovenantAppSettingsFile, optional: false, reloadOnChange: false); config.AddEnvironmentVariables(); }) .ConfigureLogging((hostingContext, logging) => { logging.ClearProviders(); logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddFilter("System", LogLevel.Warning) .AddFilter("Microsoft", LogLevel.Warning); }) .UseStartup <Startup>() .UseSetting("CovenantUri", CovenantUri) .UseSetting("CovenantUsername", CovenantUsername) .UseSetting("CovenantPassword", CovenantPassword) .Build();
/// <inheritdoc /> public override bool MaterializeFrame(MediaFrame input, ref MediaBlock output, MediaBlock previousBlock) { if (output == null) { output = new VideoBlock(); } if (input is VideoFrame == false || output is VideoBlock == false) { throw new ArgumentNullException($"{nameof(input)} and {nameof(output)} are either null or not of a compatible media type '{MediaType}'"); } var source = (VideoFrame)input; var target = (VideoBlock)output; // Retrieve a suitable scaler or create it on the fly var newScaler = ffmpeg.sws_getCachedContext( Scaler, source.Pointer->width, source.Pointer->height, NormalizePixelFormat(source.Pointer), source.Pointer->width, source.Pointer->height, Constants.VideoPixelFormat, ScalerFlags, null, null, null); // if it's the first time we set the scaler, simply assign it. if (Scaler == null) { Scaler = newScaler; RC.Current.Add(Scaler); } // Reassign to the new scaler and remove the reference to the existing one // The get cached context function automatically frees the existing scaler. if (Scaler != newScaler) { RC.Current.Remove(Scaler); Scaler = newScaler; } // Perform scaling and save the data to our unmanaged buffer pointer if (target.Allocate(source, Constants.VideoPixelFormat) && target.TryAcquireWriterLock(out var writeLock)) { using (writeLock) { var targetStride = new[] { target.PictureBufferStride }; var targetScan = default(byte_ptrArray8); targetScan[0] = (byte *)target.Buffer; // The scaling is done here var outputHeight = ffmpeg.sws_scale( Scaler, source.Pointer->data, source.Pointer->linesize, 0, source.Pointer->height, targetScan, targetStride); if (outputHeight <= 0) { return(false); } } } else { return(false); } // After scaling, we need to copy and guess some of the block properties // Flag the block if we have to target.IsStartTimeGuessed = source.HasValidStartTime == false; // Try to fix the start time, duration and End time if we don't have valid data if (source.HasValidStartTime == false && previousBlock != null) { // Get timing information from the previous block target.StartTime = TimeSpan.FromTicks(previousBlock.EndTime.Ticks + 1); target.Duration = source.Duration.Ticks > 0 ? source.Duration : previousBlock.Duration; target.EndTime = TimeSpan.FromTicks(target.StartTime.Ticks + target.Duration.Ticks); // Guess picture number and SMTPE var frameRate = ffmpeg.av_guess_frame_rate(Container.InputContext, Stream, source.Pointer); target.DisplayPictureNumber = Utilities.ComputePictureNumber(StartTime, target.StartTime, frameRate); target.SmtpeTimeCode = Utilities.ComputeSmtpeTimeCode(target.DisplayPictureNumber, frameRate); } else { // We set the target properties directly from the source target.StartTime = source.StartTime; target.Duration = source.Duration; target.EndTime = source.EndTime; // Copy picture number and SMTPE target.DisplayPictureNumber = source.DisplayPictureNumber; target.SmtpeTimeCode = source.SmtpeTimeCode; } // Fill out other properties target.IsHardwareFrame = source.IsHardwareFrame; target.HardwareAcceleratorName = source.HardwareAcceleratorName; target.CompressedSize = source.CompressedSize; target.CodedPictureNumber = source.CodedPictureNumber; target.StreamIndex = source.StreamIndex; target.ClosedCaptions = source.ClosedCaptions.ToList(); // Update the stream info object if we get Closed Caption Data if (StreamInfo.HasClosedCaptions == false && target.ClosedCaptions.Count > 0) { StreamInfo.HasClosedCaptions = true; } // Process the aspect ratio var aspectRatio = ffmpeg.av_guess_sample_aspect_ratio(Container.InputContext, Stream, source.Pointer); if (aspectRatio.num == 0 || aspectRatio.den == 0) { target.PixelAspectWidth = 1; target.PixelAspectHeight = 1; } else { target.PixelAspectWidth = aspectRatio.num; target.PixelAspectHeight = aspectRatio.den; } return(true); }
public void Dispose() { Utilities.Dispose(ref DepthStencilView); Utilities.Dispose(ref DepthStencilTexture); }
internal static void DisposeStates() { Utilities.Dispose(ref RasterizerState); Utilities.Dispose(ref DepthStencilState); }
public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName) { //002 AX V C 01:00:01:15 01:00:04:18 00:00:01:15 00:00:04:18 //000002 AX V C 01:00:04:00 01:00:05:00 00:00:02:05 00:00:03:05 _errorCount = 0; Paragraph lastParagraph = null; int count = 0; var splitChar = new[] { ' ' }; foreach (string line in lines) { bool isTimeCode = false; if (line.Length > 0) { bool success = false; if (line.Length > 65 && line.Length < 85 && line.IndexOf(':') > 20) { var match = Regex.Match(line); if (match.Success) { isTimeCode = true; if (lastParagraph != null && Math.Abs(lastParagraph.StartTime.TotalMilliseconds + 1) > 0.001) { subtitle.Paragraphs.Add(lastParagraph); } var arr = line.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); try { if (arr.Length == 8 && arr[1] != "BL") { var start = DecodeTimeCodeFrames(arr[6], SplitCharColon); var end = DecodeTimeCodeFrames(arr[7], SplitCharColon); lastParagraph = new Paragraph(start, end, string.Empty); success = true; } else { lastParagraph = new Paragraph(string.Empty, -1, -1); } } catch { _errorCount++; } } } if (!isTimeCode && !string.IsNullOrWhiteSpace(line) && lastParagraph != null && Utilities.GetNumberOfLines(lastParagraph.Text) < 5) { lastParagraph.Text = (lastParagraph.Text + Environment.NewLine + line).Trim(); success = true; } if (!success && count > 9) { _errorCount++; } } count++; } if (lastParagraph != null) { subtitle.Paragraphs.Add(lastParagraph); } foreach (var paragraph in subtitle.Paragraphs) { if (paragraph.Text.StartsWith(TextPrefix, StringComparison.Ordinal)) { paragraph.Text = paragraph.Text.Remove(0, TextPrefix.Length).TrimStart(); } } subtitle.Renumber(); }
public void TestExecuteShellCommandFail() { var result = Utilities.ExecuteShellCommand(null, FindDotnetProcess(), "DoesnotExist.dll"); Assert.Equal(1, result.ExitCode); }
public override bool ParseBytesAndExecute(byte[] data) { if (data.Length != 4 + 4 + 4 + 24) { return(false); } string sound = TheClient.Network.Strings.StringForIndex(Utilities.BytesToInt(Utilities.BytesPartial(data, 0, 4))); float vol = Utilities.BytesToFloat(Utilities.BytesPartial(data, 4, 4)); float pitch = Utilities.BytesToFloat(Utilities.BytesPartial(data, 4 + 4, 4)); Location pos = Location.FromDoubleBytes(data, 4 + 4 + 4); TheClient.Sounds.Play(TheClient.Sounds.GetSound(sound), false, pos, pitch, vol); return(true); }
private void SplitSingle(StringBuilder sb) { string t = sb.ToString().Trim(); string[] tarr = t.Replace("\r\n", "\n").Split('\n'); if (checkBoxMergeShortLines.Checked == false && tarr.Length == 3 && tarr[0].Length < Configuration.Settings.General.SubtitleLineMaximumLength && tarr[1].Length < Configuration.Settings.General.SubtitleLineMaximumLength && tarr[2].Length < Configuration.Settings.General.SubtitleLineMaximumLength) { _subtitle.Paragraphs.Add(new Paragraph { Text = tarr[0] + Environment.NewLine + tarr[1] }); return; } if (checkBoxMergeShortLines.Checked == false && tarr.Length == 2 && tarr[0].Length < Configuration.Settings.General.SubtitleLineMaximumLength && tarr[1].Length < Configuration.Settings.General.SubtitleLineMaximumLength) { _subtitle.Paragraphs.Add(new Paragraph { Text = tarr[0] + Environment.NewLine + tarr[1] }); return; } if (checkBoxMergeShortLines.Checked == false && tarr.Length == 1 && tarr[0].Length < Configuration.Settings.General.SubtitleLineMaximumLength) { _subtitle.Paragraphs.Add(new Paragraph { Text = tarr[0].Trim() }); return; } Paragraph p = null; string threeliner; if (CanMakeThreeLiner(out threeliner, sb.ToString())) { var parts = threeliner.SplitToLines(); _subtitle.Paragraphs.Add(new Paragraph { Text = parts[0] + Environment.NewLine + parts[1] }); _subtitle.Paragraphs.Add(new Paragraph { Text = parts[2].Trim() }); return; } foreach (string text in Utilities.AutoBreakLineMoreThanTwoLines(sb.ToString(), Configuration.Settings.General.SubtitleLineMaximumLength, string.Empty).SplitToLines()) { if (p == null) { p = new Paragraph { Text = text }; } else if (p.Text.Contains(Environment.NewLine)) { _subtitle.Paragraphs.Add(p); p = new Paragraph(); if (text.Length >= Configuration.Settings.General.SubtitleLineMaximumLength) { p.Text = Utilities.AutoBreakLine(text); } else { p.Text = text; } } else { if (checkBoxMergeShortLines.Checked || p.Text.Length > Configuration.Settings.General.SubtitleLineMaximumLength || text.Length > Configuration.Settings.General.SubtitleLineMaximumLength) { p.Text = Utilities.AutoBreakLine(p.Text + Environment.NewLine + text.Trim()); } else { p.Text = p.Text + Environment.NewLine + text.Trim(); } } } if (p != null) { _subtitle.Paragraphs.Add(p); } }
public static string FixInvalidItalicTags(string text) { const string beginTag = "<i>"; const string endTag = "</i>"; text = text.Replace("< i >", beginTag); text = text.Replace("< i>", beginTag); text = text.Replace("<i >", beginTag); text = text.Replace("<I>", beginTag); text = text.Replace("< I >", beginTag); text = text.Replace("< I>", beginTag); text = text.Replace("<I >", beginTag); text = text.Replace("< / i >", endTag); text = text.Replace("< /i>", endTag); text = text.Replace("</ i>", endTag); text = text.Replace("< /i >", endTag); text = text.Replace("</i >", endTag); text = text.Replace("</ i >", endTag); text = text.Replace("< / i>", endTag); text = text.Replace("</I>", endTag); text = text.Replace("< / I >", endTag); text = text.Replace("< /I>", endTag); text = text.Replace("</ I>", endTag); text = text.Replace("< /I >", endTag); text = text.Replace("</I >", endTag); text = text.Replace("</ I >", endTag); text = text.Replace("< / I>", endTag); text = text.Replace("<I>", beginTag); text = text.Replace("</I>", endTag); text = text.Replace("</i> <i>", "_@_"); text = text.Replace(" _@_", "_@_"); text = text.Replace(" _@_ ", "_@_"); text = text.Replace("_@_", " "); if (text.Contains(beginTag)) { text = text.Replace("<i/>", endTag); text = text.Replace("<I/>", endTag); } else { text = text.Replace("<i/>", string.Empty); text = text.Replace("<I/>", string.Empty); } text = text.Replace(beginTag + beginTag, beginTag); text = text.Replace(endTag + endTag, endTag); int italicBeginTagCount = Utilities.CountTagInText(text, beginTag); int italicEndTagCount = Utilities.CountTagInText(text, endTag); int noOfLines = Utilities.GetNumberOfLines(text); if (italicBeginTagCount + italicEndTagCount > 0) { if (italicBeginTagCount == 1 && italicEndTagCount == 1 && text.IndexOf(beginTag, StringComparison.Ordinal) > text.IndexOf(endTag, StringComparison.Ordinal)) { const string pattern = "___________@"; text = text.Replace(beginTag, pattern); text = text.Replace(endTag, beginTag); text = text.Replace(pattern, endTag); } if (italicBeginTagCount == 2 && italicEndTagCount == 0) { int firstIndex = text.IndexOf(beginTag, StringComparison.Ordinal); int lastIndex = text.LastIndexOf(beginTag, StringComparison.Ordinal); int lastIndexWithNewLine = text.LastIndexOf(Environment.NewLine + beginTag, StringComparison.Ordinal) + Environment.NewLine.Length; if (noOfLines == 2 && lastIndex == lastIndexWithNewLine && firstIndex < 2) { text = text.Replace(Environment.NewLine, endTag + Environment.NewLine) + endTag; } else { text = text.Remove(lastIndex, beginTag.Length).Insert(lastIndex, endTag); } } if (italicBeginTagCount == 1 && italicEndTagCount == 2) { int firstIndex = text.IndexOf(endTag, StringComparison.Ordinal); if (text.StartsWith("</i>-<i>-", StringComparison.Ordinal) || text.StartsWith("</i>- <i>-", StringComparison.Ordinal) || text.StartsWith("</i>- <i> -", StringComparison.Ordinal) || text.StartsWith("</i>-<i> -", StringComparison.Ordinal)) { text = text.Remove(0, 5); } else if (firstIndex == 0) { text = text.Remove(0, 4); } else { text = text.Substring(0, firstIndex) + text.Substring(firstIndex + endTag.Length); } } if (italicBeginTagCount == 2 && italicEndTagCount == 1) { var lines = text.SplitToLines(); if (lines.Count == 2 && lines[0].StartsWith(beginTag, StringComparison.Ordinal) && lines[0].EndsWith(endTag, StringComparison.Ordinal) && lines[1].StartsWith(beginTag, StringComparison.Ordinal)) { text = text.TrimEnd() + endTag; } else { int lastIndex = text.LastIndexOf(beginTag, StringComparison.Ordinal); if (text.Length > lastIndex + endTag.Length) { text = text.Substring(0, lastIndex) + text.Substring(lastIndex - 1 + endTag.Length); } else { text = text.Substring(0, lastIndex - 1) + endTag; } } if (text.StartsWith(beginTag, StringComparison.Ordinal) && text.EndsWith(endTag, StringComparison.Ordinal) && text.Contains(endTag + Environment.NewLine + beginTag)) { text = text.Replace(endTag + Environment.NewLine + beginTag, Environment.NewLine); } } if (italicBeginTagCount == 1 && italicEndTagCount == 0) { int lastIndexWithNewLine = text.LastIndexOf(Environment.NewLine + beginTag, StringComparison.Ordinal) + Environment.NewLine.Length; int lastIndex = text.LastIndexOf(beginTag, StringComparison.Ordinal); if (text.StartsWith(beginTag, StringComparison.Ordinal)) { text += endTag; } else if (noOfLines == 2 && lastIndex == lastIndexWithNewLine) { text += endTag; } else { text = text.Replace(beginTag, string.Empty); } } if (italicBeginTagCount == 0 && italicEndTagCount == 1) { var cleanText = RemoveOpenCloseTags(text, TagItalic, TagBold, TagUnderline, TagCyrillicI); bool isFixed = false; // Foo.</i> if (text.EndsWith(endTag, StringComparison.Ordinal) && !cleanText.StartsWith('-') && !cleanText.Contains(Environment.NewLine + "-")) { text = beginTag + text; isFixed = true; } // - Foo</i> | - Foo. // - Bar. | - Foo.</i> if (!isFixed && Utilities.GetNumberOfLines(cleanText) == 2) { int newLineIndex = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (newLineIndex > 0) { var firstLine = text.Substring(0, newLineIndex).Trim(); var secondLine = text.Substring(newLineIndex + 2).Trim(); if (firstLine.EndsWith(endTag, StringComparison.Ordinal)) { firstLine = beginTag + firstLine; isFixed = true; } if (secondLine.EndsWith(endTag, StringComparison.Ordinal)) { secondLine = beginTag + secondLine; isFixed = true; } text = firstLine + Environment.NewLine + secondLine; } } if (!isFixed) { text = text.Replace(endTag, string.Empty); } } // - foo.</i> // - bar.</i> if (italicBeginTagCount == 0 && italicEndTagCount == 2 && text.Contains(endTag + Environment.NewLine, StringComparison.Ordinal) && text.EndsWith(endTag, StringComparison.Ordinal)) { text = text.Replace(endTag, string.Empty); text = beginTag + text + endTag; } if (italicBeginTagCount == 0 && italicEndTagCount == 2 && text.StartsWith(endTag, StringComparison.Ordinal) && text.EndsWith(endTag, StringComparison.Ordinal)) { int firstIndex = text.IndexOf(endTag, StringComparison.Ordinal); text = text.Remove(firstIndex, endTag.Length).Insert(firstIndex, beginTag); } // <i>Foo</i> // <i>Bar</i> if (italicBeginTagCount == 2 && italicEndTagCount == 2 && noOfLines == 2) { int index = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (index > 0 && text.Length > index + (beginTag.Length + endTag.Length)) { var firstLine = text.Substring(0, index).Trim(); var secondLine = text.Substring(index + Environment.NewLine.Length).Trim(); if (firstLine.Length > 10 && firstLine.StartsWith("- <i>", StringComparison.Ordinal) && firstLine.EndsWith(endTag, StringComparison.Ordinal)) { text = "<i>- " + firstLine.Remove(0, 5) + Environment.NewLine + secondLine; text = text.Replace("<i>- ", "<i>- "); index = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); firstLine = text.Substring(0, index).Trim(); secondLine = text.Substring(index + Environment.NewLine.Length).Trim(); } if (secondLine.Length > 10 && secondLine.StartsWith("- <i>", StringComparison.Ordinal) && secondLine.EndsWith(endTag, StringComparison.Ordinal)) { text = firstLine + Environment.NewLine + "<i>- " + secondLine.Remove(0, 5); text = text.Replace("<i>- ", "<i>- "); index = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); firstLine = text.Substring(0, index).Trim(); secondLine = text.Substring(index + Environment.NewLine.Length).Trim(); } if (Utilities.StartsAndEndsWithTag(firstLine, beginTag, endTag) && Utilities.StartsAndEndsWithTag(secondLine, beginTag, endTag)) { text = text.Replace(beginTag, string.Empty).Replace(endTag, string.Empty).Trim(); text = beginTag + text + endTag; } } //FALCONE:<i> I didn't think</i><br /><i>it was going to be you,</i> var colIdx = text.IndexOf(':'); if (colIdx >= 0 && Utilities.CountTagInText(text, beginTag) + Utilities.CountTagInText(text, endTag) == 4 && text.Length > colIdx + 1 && !char.IsDigit(text[colIdx + 1])) { var firstLine = text.Substring(0, index); var secondLine = text.Substring(index).TrimStart(); var secIdxCol = secondLine.IndexOf(':'); if (secIdxCol < 0 || !Utilities.IsBetweenNumbers(secondLine, secIdxCol)) { var idx = firstLine.IndexOf(':'); if (idx > 1) { var pre = text.Substring(0, idx + 1).TrimStart(); text = text.Remove(0, idx + 1); text = FixInvalidItalicTags(text).Trim(); if (text.StartsWith("<i> ", StringComparison.OrdinalIgnoreCase)) { text = Utilities.RemoveSpaceBeforeAfterTag(text, beginTag); } text = pre + " " + text; } } } } //<i>- You think they're they gone?<i> //<i>- That can't be.</i> if (italicBeginTagCount == 3 && italicEndTagCount == 1 && noOfLines == 2) { var newLineIdx = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); var firstLine = text.Substring(0, newLineIdx).Trim(); var secondLine = text.Substring(newLineIdx).Trim(); if ((Utilities.StartsAndEndsWithTag(firstLine, beginTag, beginTag) && Utilities.StartsAndEndsWithTag(secondLine, beginTag, endTag)) || (Utilities.StartsAndEndsWithTag(secondLine, beginTag, beginTag) && Utilities.StartsAndEndsWithTag(firstLine, beginTag, endTag))) { text = text.Replace(beginTag, string.Empty); text = text.Replace(endTag, string.Empty); text = text.Replace(" ", " ").Trim(); text = beginTag + text + endTag; } } if (noOfLines == 3) { var lines = text.SplitToLines(); if ((italicBeginTagCount == 3 && italicEndTagCount == 2) || (italicBeginTagCount == 2 && italicEndTagCount == 3)) { int numberOfItalics = 0; foreach (var line in lines) { if (line.StartsWith(beginTag, StringComparison.Ordinal)) { numberOfItalics++; } if (line.EndsWith(endTag, StringComparison.Ordinal)) { numberOfItalics++; } } if (numberOfItalics == 5) { // fix missing tag text = "<i>" + text.Replace("<i>", string.Empty).Replace("</i>", string.Empty) + "</i>"; } } } text = text.Replace("<i></i>", string.Empty); text = text.Replace("<i> </i>", string.Empty); text = text.Replace("<i> </i>", string.Empty); } return(text); }
private void FixDurations() { foreach (Paragraph p in _subtitle.Paragraphs) { if (p.Text.Length == 0) { p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + 2000; } else { if (radioButtonDurationAuto.Checked) { p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + (Utilities.GetOptimalDisplayMilliseconds(p.Text)); } else { p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + ((double)numericUpDownDurationFixed.Value); } } } }
public override void Serialize(GenericWriter writer) { base.Serialize(writer); Utilities.WriteVersion(writer, 0); }
public ActionResult NewBranch(FormCollection collection, Branches br, HttpPostedFileBase agentPhoto) { ViewData["BranchTypes"] = Utilities.GetBranchTypeList(); ViewData["States"] = Utilities.GetStateList(Utilities.IndiaCountryCode); ViewData["Countries"] = Utilities.GetCountryList(); if (Roles.IsUserInRole("SuperAdmin")) { ViewData["Clients"] = ClientModels.GetClientNameList(); } if (Session["ClientId"] != null) { vw_ClientList clientDetails = ClientModels.GetClientDetailsById((int)Session["ClientId"]); int branchCount = BranchModels.GetBranchesList((int)Session["ClientId"]).Count(); if (branchCount >= clientDetails.NoOfSchoolsPermitted) { ApplicationMessages msg = new ApplicationMessages("Your have reached to branch count max limit. Please contant administrator..", MessageType.Information); ViewData["Message"] = msg; return(View()); } br.ClientId = (int)Session["ClientId"]; ViewData["Zones"] = Utilities.GetZoneNameList((int)Session["ClientId"]); if (Session["ZoneId"] != null) { ViewData["Regions"] = Utilities.GetRegionNameList((int)Session["ClientId"], (int)Session["ZoneId"]); } else { ViewData["Regions"] = Utilities.GetRegionNameList((int)Session["ClientId"], null); } } if (!ModelState.IsValid) { //ModelState.AddModelError("error", "Employee Id already exists"); ApplicationMessages msg = new ApplicationMessages("Invalid entry.", MessageType.Error); ViewData["Message"] = msg; return(View()); } if (agentPhoto != null) { if (agentPhoto.ContentLength > 0) { Int32 length = agentPhoto.ContentLength; byte[] tempImage = new byte[length]; agentPhoto.InputStream.Read(tempImage, 0, length); br.Logo = tempImage;// file.InputStream; br.ContentType = agentPhoto.ContentType; } } int result = BranchModels.AddBranch(br); if (result > 0) { ApplicationMessages msg = new ApplicationMessages("New Branch saved successfully.", MessageType.Success); ViewData["Message"] = msg; } else if (result == -1) { ApplicationMessages msg = new ApplicationMessages("Duplicate Branch Code. Please try with new Branch Code.", MessageType.Error); ViewData["Message"] = msg; } else { ApplicationMessages msg = new ApplicationMessages("Failed to create a new Branch. Please try again.", MessageType.Faild); ViewData["Message"] = msg; } return(View()); }
public ActionResult Close(int id, FormCollection collection, Branches br, HttpPostedFileBase agentPhoto) { ViewData["BranchTypes"] = Utilities.GetBranchTypeList(); ViewData["States"] = Utilities.GetStateList(Utilities.IndiaCountryCode); ViewData["Countries"] = Utilities.GetCountryList(); if (Roles.IsUserInRole("SuperAdmin")) { ViewData["Clients"] = ClientModels.GetClientNameList(); } if (Session["ClientId"] != null) { br.ClientId = (int)Session["ClientId"]; ViewData["Zones"] = Utilities.GetZoneNameList((int)Session["ClientId"]); if (Session["ZoneId"] != null) { ViewData["Regions"] = Utilities.GetRegionNameList((int)Session["ClientId"], (int)Session["ZoneId"]); } else { ViewData["Regions"] = Utilities.GetRegionNameList((int)Session["ClientId"], null); } List <vw_Branches> brList = new List <vw_Branches>(); brList = BranchModels.GetBranchesList((int)Session["ClientId"]); if (brList.Any(bl => bl.Id == id)) { ViewData.Model = BranchModels.GetBranchById((int)id); } } if (!ModelState.IsValid) { //ModelState.AddModelError("error", "Employee Id already exists"); ApplicationMessages msg = new ApplicationMessages("Invalid entry.", MessageType.Error); ViewData["Message"] = msg; return(View()); } //if (agentPhoto != null) //{ // if (agentPhoto.ContentLength > 0) // { // Int32 length = agentPhoto.ContentLength; // byte[] tempImage = new byte[length]; // agentPhoto.InputStream.Read(tempImage, 0, length); // br.Logo = tempImage;// file.InputStream; // br.ContentType = agentPhoto.ContentType; // } //} int result = BranchModels.CloseBranch(br); if (result > 0) { ApplicationMessages msg = new ApplicationMessages("Branch closed successfully.", MessageType.Success); ViewData["Message"] = msg; } else if (result == -1) { ApplicationMessages msg = new ApplicationMessages("Failed to close Branch. Please try again.", MessageType.Error); ViewData["Message"] = msg; } else { ApplicationMessages msg = new ApplicationMessages("Failed to close Branch. Please try again.", MessageType.Faild); ViewData["Message"] = msg; } return(View()); }
public static async void FetchAndLaunchTool(string tool, Action<string> currentTaskUpdateCallback = null, Action<bool> setPercentVisibilityCallback = null, Action<int> setPercentTaskDone = null, Action<string> resultingExecutableStringCallback = null, Action failedToDownloadCallback = null, Action<Exception, string, string> errorExtractingCallback = null) { var toolName = tool.Replace(@" ", ""); var localToolFolderName = Path.Combine(Utilities.GetDataDirectory(), @"ExternalTools", toolName); var localExecutable = Path.Combine(localToolFolderName, toolName + @".exe"); bool needsDownloading = !File.Exists(localExecutable); if (!needsDownloading && ToolsCheckedForUpdatesInThisSession.Contains(tool)) { //Don't check for updates again. resultingExecutableStringCallback?.Invoke(localExecutable); return; } currentTaskUpdateCallback?.Invoke(M3L.GetString(M3L.string_checkingForUpdates)); var latestRelease = await FetchLatestRelease(tool); //Failed to get release check if (latestRelease == null) { if (!needsDownloading) { resultingExecutableStringCallback?.Invoke(localExecutable); return; } else { //Must run on UI thread //MessageBox.Show($"Unable to download {tool}.\nPlease check your network connection and try again.\nIf the issue persists, please come to the ME3Tweaks Discord."); Log.Error(@"Unable to launch tool - could not download, and does not exist locally: " + localExecutable); failedToDownloadCallback?.Invoke(); return; } } //Got a release if (needsDownloading) { DownloadTool(localToolFolderName, tool, latestRelease, localExecutable, s => currentTaskUpdateCallback?.Invoke(s), vis => setPercentVisibilityCallback?.Invoke(vis), percent => setPercentTaskDone?.Invoke(percent), exe => resultingExecutableStringCallback?.Invoke(exe), (exception, message, caption) => errorExtractingCallback?.Invoke(exception ,message, caption) ); } else { //Check if it need updated FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(localExecutable); bool needsUpdated = false; if (tool == MEM || tool == MEM_CMD) { //Checks based on major int releaseVer = int.Parse(latestRelease.TagName); if (releaseVer > fvi.ProductMajorPart) { needsUpdated = true; } } else { Version serverVersion = new Version(latestRelease.TagName); Version localVersion = new Version($@"{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"); if (serverVersion > localVersion) { needsUpdated = true; } } if (!needsUpdated) { resultingExecutableStringCallback?.Invoke(localExecutable); } else { DownloadTool(localToolFolderName, tool, latestRelease, localExecutable, s => currentTaskUpdateCallback?.Invoke(s), vis => setPercentVisibilityCallback?.Invoke(vis), percent => setPercentTaskDone?.Invoke(percent), exe => resultingExecutableStringCallback?.Invoke(exe), (exception, message, caption) => errorExtractingCallback?.Invoke(exception, message, caption) ); } ToolsCheckedForUpdatesInThisSession.Add(tool); } }
private bool GetIsSameUser(ClaimsPrincipal user, string targetUserId) { return(Utilities.GetUserId(user) == targetUserId); }
public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName) { _errorCount = 0; Paragraph p = null; subtitle.Paragraphs.Clear(); foreach (string line in lines) { string s = line.Trim(); var match = RegexTimeCodes2.Match(s); if (match.Success) { s = s.Substring(0, match.Index + 13).Trim(); } match = RegexTimeCodes1.Match(s); if (match.Success && match.Index > 13) { string text = s.Substring(0, match.Index).Trim(); string timeCode = s.Substring(match.Index).Trim(); string[] startParts = timeCode.Split(SplitCharColon, StringSplitOptions.RemoveEmptyEntries); if (startParts.Length == 4) { try { p = new Paragraph(DecodeTimeCodeFramesFourParts(startParts), new TimeCode(), text); subtitle.Paragraphs.Add(p); } catch (Exception exception) { _errorCount++; System.Diagnostics.Debug.WriteLine(exception.Message); } } } else if (string.IsNullOrWhiteSpace(line) || RegexTimeCodes1.IsMatch(" " + s)) { // skip empty lines } else if (!string.IsNullOrWhiteSpace(line) && p != null) { _errorCount++; } } for (int i = 0; i < subtitle.Paragraphs.Count; i++) { Paragraph current = subtitle.Paragraphs[i]; Paragraph next = subtitle.GetParagraphOrDefault(i + 1); if (next != null) { current.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines; } else { current.EndTime.TotalMilliseconds = current.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(current.Text); } if (current.Duration.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds) { current.EndTime.TotalMilliseconds = current.StartTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds; } } subtitle.RemoveEmptyLines(); subtitle.Renumber(); }
public async Task ListGuilds(int pageNumber = 1) { IReadOnlyCollection <IGuild> guilds = await Context.Client.GetGuildsAsync().ConfigureAwait(false); const int guildsPerPage = 10; int highestPage = (int)Math.Ceiling((1.0 * guilds.Count) / guildsPerPage); if (pageNumber <= 0 || pageNumber > highestPage) { throw new ArgumentOutOfRangeException(nameof(pageNumber)); } var replyBuilder = new System.Text.StringBuilder(); replyBuilder.AppendLine($"**Guild List (Page {pageNumber} of {highestPage}):**"); replyBuilder.AppendFormat("*{0}, member counts are likely inaccurate*", Utilities.Pluralize("guild", guilds.Count)).AppendLine(); replyBuilder.AppendLine(); pageNumber--; foreach (var guild in guilds.Skip(pageNumber * guildsPerPage).Take(guildsPerPage)) { var owner = await guild.GetOwnerAsync().ConfigureAwait(false); int memberCt = -1; try { memberCt = (await guild.GetUsersAsync().ConfigureAwait(false)).Count; } catch { } replyBuilder.AppendLine($"__{guild.Name}__ ({guild.Id}):\n- {Utilities.Pluralize("member", memberCt)}\n- {Utilities.Pluralize("text channel", (await guild.GetTextChannelsAsync().ConfigureAwait(false)).Count)}\n- Owned by: {(owner != null ? owner.Username + '#' + owner.DiscriminatorValue : "<unknown>")} (<{(Context.Channel is IDMChannel ? "" : "\\")}@{guild.OwnerId}>)"); } await ReplyAsync(replyBuilder.ToString()).ConfigureAwait(false); }
public void ApplySideEffect(GameObject npc, GameObject pc, int lineNumber, out string originalScript) { switch (lineNumber) { case 1: originalScript = "game.global_vars[131] = 1"; SetGlobalVar(131, 1); break; case 2: case 3: case 21: case 22: case 111: case 112: case 113: originalScript = "npc.attack( pc )"; npc.Attack(pc); break; case 4: case 5: originalScript = "game.global_flags[129] = 1"; SetGlobalFlag(129, true); break; case 8: case 9: case 63: case 65: case 73: case 74: case 75: case 76: case 165: case 166: case 261: case 262: case 291: case 292: case 376: case 383: case 384: case 403: case 404: originalScript = "game.global_flags[128] = 1"; SetGlobalFlag(128, true); break; case 24: case 25: case 123: case 124: case 151: case 152: originalScript = "game.global_flags[128] = 1; go_hideout(npc,pc)"; SetGlobalFlag(128, true); go_hideout(npc, pc); ; break; case 50: originalScript = "game.story_state = 5"; StoryState = 5; break; case 60: originalScript = "game.quests[55].state = qs_mentioned"; SetQuestState(55, QuestState.Mentioned); break; case 62: case 64: case 281: case 282: case 293: case 294: originalScript = "party_transfer_to( npc, 10402 ); party_transfer_to( npc, 2204 ); party_transfer_to( npc, 3012 )"; Utilities.party_transfer_to(npc, 10402); Utilities.party_transfer_to(npc, 2204); Utilities.party_transfer_to(npc, 3012); ; break; case 70: case 170: originalScript = "game.map_flags( 5066, 0, 1 )"; RevealTownMapMarker(5066, 0); break; case 71: case 72: case 251: case 252: originalScript = "game.quests[55].state = qs_accepted"; SetQuestState(55, QuestState.Accepted); break; case 81: case 91: case 92: case 114: case 115: case 131: case 132: case 141: case 171: case 191: originalScript = "go_hideout(npc,pc)"; go_hideout(npc, pc); break; case 100: originalScript = "game.quests[55].state = qs_completed"; SetQuestState(55, QuestState.Completed); break; case 163: case 164: originalScript = "party_transfer_to( npc, 10402 ); party_transfer_to( npc, 2204 ); party_transfer_to( npc, 3012 ); game.global_flags[128] = 0"; Utilities.party_transfer_to(npc, 10402); Utilities.party_transfer_to(npc, 2204); Utilities.party_transfer_to(npc, 3012); SetGlobalFlag(128, false); ; break; case 181: case 182: originalScript = "pc.follower_add( npc )"; pc.AddFollower(npc); break; case 202: case 203: originalScript = "game.global_flags[128] = 0; game.quests[55].state = qs_accepted"; SetGlobalFlag(128, false); SetQuestState(55, QuestState.Accepted); ; break; case 206: case 207: case 208: case 209: originalScript = "game.global_flags[128] = 0"; SetGlobalFlag(128, false); break; case 300: originalScript = "game.quests[56].state = qs_mentioned"; SetQuestState(56, QuestState.Mentioned); break; case 301: case 302: case 351: case 352: originalScript = "game.quests[56].state = qs_accepted"; SetQuestState(56, QuestState.Accepted); break; case 331: originalScript = "pc.follower_remove( npc ); go_hideout(npc,pc)"; pc.RemoveFollower(npc); go_hideout(npc, pc); ; break; case 360: originalScript = "game.quests[56].state = qs_completed"; SetQuestState(56, QuestState.Completed); break; case 361: case 362: originalScript = "party_transfer_to( npc, 2205 )"; Utilities.party_transfer_to(npc, 2205); break; case 401: case 402: originalScript = "party_transfer_to( npc, 2205 ); party_transfer_to( npc, 4005 )"; Utilities.party_transfer_to(npc, 2205); Utilities.party_transfer_to(npc, 4005); ; break; case 431: originalScript = "pc.follower_remove( npc ); disappear(npc,pc)"; pc.RemoveFollower(npc); disappear(npc, pc); ; break; default: originalScript = null; return; } }
public static Boolean GetCurrentPostingRangeDates(Int32 ALedgerNumber, out DateTime AStartDateCurrentPeriod, out DateTime AEndDateLastForwardingPeriod) { Boolean dataIsOk = false; #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments DateTime StartDateCurrentPeriod = new DateTime(); DateTime EndDateLastForwardingPeriod = new DateTime(); TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("GetCurrentPostingRangeDates"); db.ReadTransaction( ref Transaction, delegate { ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); #region Validate Data if ((ledgerTable == null) || (ledgerTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data int firstPostingPeriod = -1; int lastPostingPeriod = -1; // If final month end has been run but year end has not yet been run // then we cannot post to the current period as it is actually closed. if (ledgerTable[0].ProvisionalYearEndFlag) { firstPostingPeriod = ledgerTable[0].CurrentPeriod + 1; } else { firstPostingPeriod = ledgerTable[0].CurrentPeriod; } AAccountingPeriodTable accountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber, firstPostingPeriod, Transaction); #region Validate Data 2 if ((accountingPeriodTable == null) || (accountingPeriodTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Accounting Period data for Ledger number {1} and posting period {2} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber, firstPostingPeriod)); } #endregion Validate Data 2 StartDateCurrentPeriod = accountingPeriodTable[0].PeriodStartDate; lastPostingPeriod = ledgerTable[0].CurrentPeriod + ledgerTable[0].NumberFwdPostingPeriods; accountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber, lastPostingPeriod, Transaction); #region Validate Data 3 if ((accountingPeriodTable == null) || (accountingPeriodTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Accounting Period data for Ledger number {1} and posting period {2} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber, lastPostingPeriod)); } #endregion Validate Data 3 EndDateLastForwardingPeriod = accountingPeriodTable[0].PeriodEndDate; dataIsOk = true; }); AStartDateCurrentPeriod = StartDateCurrentPeriod; AEndDateLastForwardingPeriod = EndDateLastForwardingPeriod; db.CloseDBConnection(); return(dataIsOk); }
public static T Get <T>(ICallbackEvento callback, object parametros) { try { logger.Info("Ativador.Get<" + typeof(T).ToString() + ">()"); // Pega config if (_config == null) { _config = GerenciadorConfig.ReceberConfig <AtivadorConfig>(); } // Pega config do host, caso exista if (_configServicoHost == null) { if (ServicoHostColecao.Default.IdConfigCarregado != null) { _configServicoHost = GerenciadorConfig.ReceberConfig <ServicoHostConfig>( ServicoHostColecao.Default.IdConfigCarregado); } } // Inicializa T servico = default(T); Type tipo = typeof(T); ServicoInfo servicoInfo = null; // Verifica se tem no cache bool adicionarNoCache = false; lock (_cache) { if (_cache.ContainsKey(typeof(T))) { servicoInfo = _cache[typeof(T)]; } else { adicionarNoCache = true; } } // Verifica se tem na lista interna if (servicoInfo == null && _config != null) { logger.Info("Buscando informacoes do servico " + tipo.FullName + " na lista interna"); servicoInfo = _findServicoInfo(tipo.FullName, _config.Servicos); } // Verifica se tem na lista de servicos do host if (servicoInfo == null && _configServicoHost != null) { logger.Info("Buscando informacoes do servico " + tipo.FullName + " na lista de servicos do host"); servicoInfo = _findServicoInfo(tipo.FullName, _configServicoHost.Servicos); } // Se ainda não achou, pega serviço info no localizador if (servicoInfo == null) { logger.Info("Buscando informacoes do servico " + tipo.FullName + " no localizador"); servicoInfo = LocalizadorCliente.Consultar(typeof(T)); } // Se até este ponto não achou o serviçoInfo, dispara erro if (servicoInfo == null) { logger.Error("Não foi possível conseguir informações para a ativação do serviço " + tipo.FullName); throw new Exception("Não foi possível conseguir informações para a ativação do serviço " + tipo.FullName + "."); } // Verifica se deve adicionar no cache if (adicionarNoCache && servicoInfo != null) { lock (_cache) { if (!_cache.ContainsKey(typeof(T))) { logger.Info("Armazenando informacoes do servico " + tipo.FullName + " no cache"); _cache.Add(typeof(T), servicoInfo); } } } // Primeira tentativa deve ser criação local? if (servicoInfo.AtivacaoDefaultTipo == ServicoAtivacaoTipo.Local) { logger.Debug("Ativando " + tipo.FullName + " localmente"); // Cria o serviço servico = ServicoHostColecao.Default.ReceberServico <T>(); // Caso seja servico com callback, faz a chamada do registro IServicoComCallback servicoComCallback = servico as IServicoComCallback; if (servicoComCallback != null && callback != null) { servicoComCallback.Registrar(parametros, callback); } } if (servico == null && servicoInfo.EndPoints.Count > 0) { ContractDescription cd; logger.Debug("Ativando " + tipo.FullName + " como WCF"); string epaddress = _findEndpointForInterface <T>(servicoInfo); logger.Debug("Criando Binding para Endpoint: " + epaddress); // Cria via wcf Binding binding = Utilities.GetBinding(epaddress); //(Binding) // typeof(BasicHttpBinding).Assembly.CreateInstance( // servicoInfo.EndPoints[0].NomeBindingType); binding.ReceiveTimeout = new TimeSpan(0, 2, 0); binding.SendTimeout = new TimeSpan(0, 1, 0); binding.OpenTimeout = new TimeSpan(0, 0, 30); binding.CloseTimeout = new TimeSpan(0, 0, 30); if (servicoInfo.EndPoints[0].NomeBindingType.Equals("System.ServiceModel.NetTcpBinding")) { ((NetTcpBinding)binding).MaxReceivedMessageSize = 8000000; ((NetTcpBinding)binding).ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; //((NetTcpBinding)binding).Security.Mode = SecurityMode.None; } if (servicoInfo.EndPoints[0].NomeBindingType.Equals("System.ServiceModel.BasicHttpBinding")) { logger.Debug("Binding setado BasicHttpBinding , verificando por callback"); ((BasicHttpBinding)binding).MaxReceivedMessageSize = int.MaxValue; ((BasicHttpBinding)binding).ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; //((NetTcpBinding)binding).Security.Mode = SecurityMode.None; } logger.Debug("Binding criado, verificando por callback"); // Verifica se tem callback // Mesmo que não tenha informado, tem que ver se tem contrato especificado na interface bool temCallback = callback != null; if (!temCallback) { object[] attrs = typeof(T).GetCustomAttributes(typeof(ServiceContractAttribute), true); if (attrs.Length == 1) { if (((ServiceContractAttribute)attrs[0]).CallbackContract != null) { temCallback = true; } } } // Cria dependendo se tem contrato ou não if (!temCallback) { logger.Debug("Servico " + tipo.FullName + " nao tem callback, criando channel "); IChannelFactory <T> canal = new ChannelFactory <T>(binding); canal.Faulted += new EventHandler(_channelFaulted); string uri = _findEndpointForInterface <T>(servicoInfo); if (uri == null) { string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n"; msg += "Verifique se existe <ServicoEndPointInfo> nas configuracoes locais,\n"; msg += "ou se um endpoint foi criado para o mesmo e registrado no ServicoLocalizador."; logger.Error("ERRO: NENHUM ENDERECO DE ENDPOINT PARA SERVICO [" + tipo.FullName + "]!"); throw new Exception(msg); } servico = canal.CreateChannel(new EndpointAddress(uri)); cd = ((ChannelFactory)canal).Endpoint.Contract; } else { logger.Debug("Servico " + tipo.FullName + " tem callback, criando channel duplex"); DuplexChannelFactory <T> canal = null; canal.Faulted += new EventHandler(_channelFaulted); if (callback == null) { logger.Error("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback."); throw new Exception("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback."); } canal = new DuplexChannelFactory <T>(new InstanceContext(callback), binding); string uri = _findEndpointForInterface <T>(servicoInfo); if (uri == null) { string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n"; msg += "Verifique se existe <ServicoEndPointInfo> nas configuracoes locais,\n"; msg += "ou se um endpoint foi criado para o mesmo e registrado no ServicoLocalizador."; logger.Error("ERRO: NENHUM ENDERECO DE ENDPOINT PARA SERVICO [" + tipo.FullName + "]!"); throw new Exception(msg); } servico = canal.CreateChannel(new EndpointAddress(uri)); cd = canal.Endpoint.Contract; IServicoComCallback servicoComCallback = servico as IServicoComCallback; if (servicoComCallback != null) { servicoComCallback.Registrar(parametros); } } if (cd != null) { foreach (OperationDescription od in cd.Operations) { DataContractSerializerOperationBehavior serializerBh = od.Behaviors.Find <DataContractSerializerOperationBehavior>(); if (serializerBh == null) { logger.Info("Adicionando DataContractSerializerOperationBehavior"); serializerBh = new DataContractSerializerOperationBehavior(od); od.Behaviors.Add(serializerBh); } logger.Info("Setando MaxItemsInObjectGraph para operacao: " + od.Name); serializerBh.MaxItemsInObjectGraph = 8000000; } } ((IContextChannel)servico).OperationTimeout = new TimeSpan(0, 10, 0); } if (servico == null) { string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n"; msg += "Verifique se existe <servicoinfo> nas configuracoes locais,\n"; msg += "ou se o mesmo foi registrado no ServicoLocalizador e seu hoster esta ativo."; logger.Error("ERRO: SERVICO [" + tipo.FullName + "] NAO FOI ATIVADO!!!"); throw new Exception(msg); } // Retorna return(servico); } catch (Exception ex) { logger.Error("Erro em Ativador.Get(" + typeof(T).FullName + ")", ex); throw ex; } }
// Token: 0x06000049 RID: 73 RVA: 0x00003528 File Offset: 0x00001728 protected void RenderColumn(TextWriter writer, ColumnId columnId, int itemIndex, bool isBold, bool openForCompose) { if (writer == null) { throw new ArgumentNullException("writer"); } if (itemIndex < 0 || itemIndex >= this.dataSource.RangeCount) { throw new ArgumentOutOfRangeException("itemIndex", itemIndex.ToString()); } Column column = ListViewColumns.GetColumn(columnId); switch (columnId) { case ColumnId.MailIcon: if (!this.RenderIcon(writer, itemIndex)) { goto IL_857; } goto IL_857; case ColumnId.From: case ColumnId.To: { string itemPropertyString = this.dataSource.GetItemPropertyString(itemIndex, column[0]); if (itemPropertyString.Length != 0) { Utilities.CropAndRenderText(writer, itemPropertyString, 16); goto IL_857; } goto IL_857; } case ColumnId.Subject: { writer.Write("<h1"); if (isBold) { writer.Write(" class=\"bld\""); } writer.Write(">"); writer.Write("<a href=\"#\""); this.RenderFolderNameTooltip(writer, itemIndex); writer.Write(" onClick=\"onClkRdMsg(this, '"); string s = this.dataSource.GetItemProperty(itemIndex, StoreObjectSchema.ItemClass) as string; Utilities.HtmlEncode(Utilities.JavascriptEncode(s), writer); writer.Write("', {0}, {1});\">", itemIndex, openForCompose ? 1 : 0); string itemPropertyString2 = this.dataSource.GetItemPropertyString(itemIndex, column[0]); if (string.IsNullOrEmpty(itemPropertyString2.Trim())) { writer.Write(LocalizedStrings.GetHtmlEncoded(730745110)); } else { Utilities.CropAndRenderText(writer, itemPropertyString2, 32); } writer.Write("</a></h1>"); goto IL_857; } case ColumnId.Department: case ColumnId.ContactIcon: case ColumnId.BusinessPhone: case ColumnId.BusinessFax: case ColumnId.MobilePhone: case ColumnId.HomePhone: goto IL_74A; case ColumnId.HasAttachment: { bool hasAttachments = false; object itemProperty = this.dataSource.GetItemProperty(itemIndex, ItemSchema.HasAttachment); if (itemProperty is bool) { hasAttachments = (bool)itemProperty; } if (!ListViewContentsRenderingUtilities.RenderHasAttachments(writer, this.userContext, hasAttachments)) { goto IL_857; } goto IL_857; } case ColumnId.Importance: { Importance importance = Importance.Normal; object itemProperty2 = this.dataSource.GetItemProperty(itemIndex, ItemSchema.Importance); if (itemProperty2 is Importance || itemProperty2 is int) { importance = (Importance)itemProperty2; } if (!ListViewContentsRenderingUtilities.RenderImportance(writer, this.UserContext, importance)) { goto IL_857; } goto IL_857; } case ColumnId.DeliveryTime: { ExDateTime itemPropertyExDateTime = this.dataSource.GetItemPropertyExDateTime(itemIndex, ItemSchema.ReceivedTime); if (!this.RenderDate(writer, itemPropertyExDateTime)) { goto IL_857; } goto IL_857; } case ColumnId.SentTime: { ExDateTime itemPropertyExDateTime2 = this.dataSource.GetItemPropertyExDateTime(itemIndex, ItemSchema.SentTime); if (!this.RenderDate(writer, itemPropertyExDateTime2)) { goto IL_857; } goto IL_857; } case ColumnId.Size: { int num = 0; object itemProperty3 = this.dataSource.GetItemProperty(itemIndex, ItemSchema.Size); if (itemProperty3 is int) { num = (int)itemProperty3; } Utilities.RenderSizeWithUnits(writer, (long)num, true); goto IL_857; } case ColumnId.FileAs: break; case ColumnId.Title: case ColumnId.CompanyName: goto IL_5B5; case ColumnId.PhoneNumbers: if (!this.RenderPhoneNumberColumn(writer, itemIndex)) { goto IL_857; } goto IL_857; case ColumnId.EmailAddresses: { Participant[] array = new Participant[3]; bool flag = false; array[0] = (this.dataSource.GetItemProperty(itemIndex, ContactSchema.Email1) as Participant); array[1] = (this.dataSource.GetItemProperty(itemIndex, ContactSchema.Email2) as Participant); array[2] = (this.dataSource.GetItemProperty(itemIndex, ContactSchema.Email3) as Participant); foreach (Participant participant in array) { if (participant != null && !string.IsNullOrEmpty(participant.EmailAddress)) { string text = null; string text2 = null; ContactUtilities.GetParticipantEmailAddress(participant, out text, out text2); Utilities.CropAndRenderText(writer, text, 24); flag = true; break; } } if (!flag) { goto IL_857; } goto IL_857; } default: { switch (columnId) { case ColumnId.CheckBox: { VersionedId itemPropertyVersionedId = this.dataSource.GetItemPropertyVersionedId(itemIndex, ItemSchema.Id); ListViewContentsRenderingUtilities.RenderCheckBox(writer, itemPropertyVersionedId.ObjectId.ToBase64String()); string itemClass = this.dataSource.GetItemProperty(itemIndex, StoreObjectSchema.ItemClass) as string; if (ObjectClass.IsMeetingRequest(itemClass) || ObjectClass.IsMeetingCancellation(itemClass)) { if (this.meetingMessageIdStringBuilder.Length > 0) { this.meetingMessageIdStringBuilder.Append(","); } this.meetingMessageIdStringBuilder.Append(itemPropertyVersionedId.ObjectId.ToBase64String()); goto IL_857; } goto IL_857; } case ColumnId.CheckBoxContact: case ColumnId.CheckBoxAD: { string arg; if (columnId == ColumnId.CheckBoxAD) { arg = Utilities.GetBase64StringFromGuid((Guid)this.dataSource.GetItemProperty(itemIndex, ADObjectSchema.Guid)); } else { VersionedId itemPropertyVersionedId2 = this.dataSource.GetItemPropertyVersionedId(itemIndex, ItemSchema.Id); arg = itemPropertyVersionedId2.ObjectId.ToBase64String(); } writer.Write("<input type=\"checkbox\" name=\"chkRcpt\" value=\"{0}\"", arg); writer.Write(" onClick=\"onClkRChkBx(this);\">"); goto IL_857; } case ColumnId.ADIcon: case ColumnId.BusinessFaxAD: case ColumnId.BusinessPhoneAD: case ColumnId.DepartmentAD: goto IL_74A; case ColumnId.AliasAD: break; case ColumnId.CompanyAD: goto IL_5B5; case ColumnId.DisplayNameAD: goto IL_383; default: switch (columnId) { case ColumnId.PhoneAD: break; case ColumnId.TitleAD: goto IL_5B5; default: goto IL_74A; } break; } string text3 = this.dataSource.GetItemProperty(itemIndex, column[0]) as string; if (!string.IsNullOrEmpty(text3)) { Utilities.CropAndRenderText(writer, text3, 24); goto IL_857; } goto IL_857; } } IL_383: StringBuilder stringBuilder = new StringBuilder(); object obj; int num2; if (columnId == ColumnId.DisplayNameAD) { string value = this.dataSource.GetItemProperty(itemIndex, ADRecipientSchema.DisplayName) as string; if (!string.IsNullOrEmpty(value)) { stringBuilder.Append(value); } obj = Utilities.GetBase64StringFromGuid((Guid)this.dataSource.GetItemProperty(itemIndex, ADObjectSchema.Guid)); num2 = (isBold ? 2 : 1); } else { string value = this.dataSource.GetItemProperty(itemIndex, ContactBaseSchema.FileAs) as string; if (!string.IsNullOrEmpty(value)) { stringBuilder.Append(value); } bool flag2 = (columnId == ColumnId.DisplayNameAD) ? this.userContext.IsPhoneticNamesEnabled : Utilities.IsJapanese; if (flag2) { string value2 = this.dataSource.GetItemProperty(itemIndex, ContactSchema.YomiFirstName) as string; string value3 = this.dataSource.GetItemProperty(itemIndex, ContactSchema.YomiLastName) as string; bool flag3 = false; if (stringBuilder.Length > 0 && (!string.IsNullOrEmpty(value3) || !string.IsNullOrEmpty(value2))) { stringBuilder.Append(" ("); flag3 = true; } if (!string.IsNullOrEmpty(value3)) { stringBuilder.Append(value3); if (!string.IsNullOrEmpty(value2)) { stringBuilder.Append(" "); } } if (!string.IsNullOrEmpty(value2)) { stringBuilder.Append(value2); } if (flag3) { stringBuilder.Append(")"); } } VersionedId itemPropertyVersionedId3 = this.dataSource.GetItemPropertyVersionedId(itemIndex, ItemSchema.Id); obj = itemPropertyVersionedId3.ObjectId.ToBase64String(); num2 = (isBold ? 4 : 3); } if (Utilities.WhiteSpaceOnlyOrNullEmpty(stringBuilder.ToString())) { stringBuilder.Append(LocalizedStrings.GetNonEncoded(-808148510)); } writer.Write("<h1"); if (isBold) { writer.Write(" class=\"bld\""); } writer.Write("><a href=\"#\" id=\"{0}\"", obj.ToString()); if (isBold) { writer.Write(" class=\"lvwdl\""); } this.RenderFolderNameTooltip(writer, itemIndex); writer.Write(" onClick=\"return onClkRcpt(this, {0});\">", num2); if (isBold) { ListViewContentsRenderingUtilities.RenderItemIcon(writer, this.userContext, "IPM.DistList"); } Utilities.CropAndRenderText(writer, stringBuilder.ToString(), 32); writer.Write("</a></h1>"); goto IL_857; IL_5B5: string text4 = this.dataSource.GetItemProperty(itemIndex, column[0]) as string; if (!string.IsNullOrEmpty(text4)) { Utilities.CropAndRenderText(writer, text4, 16); goto IL_857; } goto IL_857; IL_74A: object itemProperty4 = this.dataSource.GetItemProperty(itemIndex, column[0]); string text5 = itemProperty4 as string; if (itemProperty4 is ExDateTime) { writer.Write(((ExDateTime)itemProperty4).ToString()); } else if (itemProperty4 is DateTime) { ExDateTime exDateTime = new ExDateTime(this.userContext.TimeZone, (DateTime)itemProperty4); writer.Write(exDateTime.ToString()); } else if (text5 != null) { if (text5.Length != 0) { Utilities.HtmlEncode(text5, writer); } } else if (itemProperty4 is int) { Utilities.HtmlEncode(((int)itemProperty4).ToString(CultureInfo.CurrentCulture.NumberFormat), writer); } else if (itemProperty4 is Unlimited <int> ) { Unlimited <int> unlimited = (Unlimited <int>)itemProperty4; if (!unlimited.IsUnlimited) { Utilities.HtmlEncode(unlimited.Value.ToString(CultureInfo.CurrentCulture.NumberFormat), writer); } } else if (!(itemProperty4 is PropertyError)) { } IL_857: writer.Write(" "); }
// Token: 0x0600004A RID: 74 RVA: 0x00003D98 File Offset: 0x00001F98 private void RenderFolderNameTooltip(TextWriter writer, int itemIndex) { if (this.showFolderNameTooltip) { writer.Write(" title=\""); string itemPropertyString = this.dataSource.GetItemPropertyString(itemIndex, ItemSchema.ParentDisplayName); writer.Write(string.Format(LocalizedStrings.GetHtmlEncoded(699235260), Utilities.HtmlEncode(itemPropertyString))); writer.Write('"'); } }
/// <summary> /// Loads from XML. /// </summary> /// <param name="xmlContent">Content of the XML.</param> /// <returns></returns> public FSMVConfig LoadFromXML(string xmlContent) { FSMVConfig fsmvConfigs = Utilities.FromXmlString <FSMVConfig>(xmlContent); return(fsmvConfigs); }