public JObject Method(Functions funcName, JObject request, MethodCheckRequestParameters check) { if (!string.IsNullOrEmpty(Token)) request[FieldKeyword.Token] = Token; if (!string.IsNullOrEmpty(Language)) request[FieldKeyword.Language] = Language; JObject response = new JObject(); if (ServerAddr==null|| request == null || (check != null && !check(request))) { response[FieldKeyword.Success] = false; response[FieldKeyword.CommonError] = ErrorNumber.CommonBadParameter.ToString(); return response; } var webBinding = new WebHttpBinding(); webBinding.AllowCookies = true; webBinding.MaxReceivedMessageSize = 1000 * 1024 * 1024; webBinding.ReaderQuotas.MaxStringContentLength = 1000 * 1024 * 1024; webBinding.SendTimeout = new TimeSpan(0, 500, 0); webBinding.ReceiveTimeout = new TimeSpan(0, 500, 0); using (var factory = new WebChannelFactory<IService>(webBinding, ServerAddr)) { factory.Endpoint.Behaviors.Add(new WebHttpBehavior()); var session = factory.CreateChannel(); if (session == null || (session as IContextChannel)==null) { response[FieldKeyword.Success] = false; response[FieldKeyword.CommonError] = ErrorNumber.CommonBadContext.ToString(); } else using (OperationContextScope scope = new OperationContextScope(session as IContextChannel)) { var temp = request.ToString(); Stream stream = new MemoryStream(KORT.Util.Tools.GZipCompress(Encoding.UTF8.GetBytes(temp))); System.Diagnostics.Debug.WriteLine(request.ToString()); try { using (var responseStream = session.Method(funcName.ToString(), stream)) { using (var decompressStream = new MemoryStream()) { KORT.Util.Tools.GZipDecompress(responseStream, decompressStream); decompressStream.Position = 0; StreamReader reader = new StreamReader(decompressStream, Encoding.UTF8); string text = reader.ReadToEnd(); System.Diagnostics.Debug.WriteLine(text); response = JObject.Parse(text); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); response[FieldKeyword.Success] = false; response[FieldKeyword.CommonError] = ErrorNumber.Other.ToString(); response[FieldKeyword.ErrorDetail] = e.Message; } } return response; } }
private async void setup() { Functions functions = new Functions(); JsonValue list = await functions.getBookings (this.Student.StudentID.ToString()); JsonValue results = list ["Results"]; tableItems = new List<Booking>(); if (list ["IsSuccess"]) { for (int i = 0; i < results.Count; i++) { if (DateTime.Parse (results [i] ["ending"]) < DateTime.Now) { Booking b = new Booking (results [i]); if (b.BookingArchived == null) { tableItems.Add (b); } } } tableItems.Sort((x, y) => DateTime.Compare(x.StartDate, y.StartDate)); this.TableView.ReloadData (); } else { createAlert ("Timeout expired", "Please reload view"); } if (tableItems.Count == 0) { createAlert ("No Bookings", "You do not have any past bookings"); } }
private async void setup() { Functions functions = new Functions(); JsonValue list; if (SearchData == null) { list = await functions.getWorkshops ("WorkshopSetId=" +WorkshopSetID.ToString()+ "&StartingDtBegin=" + DateTime.Now.ToString("yyyy-MM-dd") + "&StartingDtEnd=" + DateTime.Now.AddYears(1).ToString("yyyy-MM-dd")); } else { list = await functions.getWorkshops (SearchData); } JsonValue results = list ["Results"]; tableItems = new List<Workshop>(); if (list ["IsSuccess"]) { for (int i = 0; i < results.Count; i++) { Workshop w = new Workshop (results [i]); if (w.Archived == null && w.StartDate > DateTime.Now) { tableItems.Add (w); } } tableItems.Sort((x, y) => DateTime.Compare(x.StartDate, y.StartDate)); this.TableView.ReloadData (); } else { createAlert ("Timeout expired", "Please reload view"); } if (tableItems.Count == 0) { createAlert ("Sorry", "There are no workshops available in this set"); } }
public AbstractNeuron(int inputCount, INeuronInitilizer init, Functions.IActivationFunction function) { Inputs = inputCount; Weights = new double[inputCount]; ActivationFunction = function; Initializer = init; Initialize(); }
/// <summary> /// Asnyc Manager for handling CSDK memory objects /// </summary> /// <param name="func">Type of function provoked</param> /// <param name="memtypes">Memory type provoking</param> /// <param name="data">Handler or Memory assigned</param> /// <param name="name">Name of memory accessing</param> public async void Manage(Functions func, MemTypes memtypes, Object data, string name = null) { if (name == null) return; if (memtypes == MemTypes.Handler) await Modify (func, name, (Handler)data); else await Modify (func, name, (Memory)data); }
public override IAliasedExpression Visit(Functions.Exec item) { writer.Write(item.MethodName); writer.Write("('"); //Potential bug if a single is generated inside the parameters VisitArray(item.Parameters, Visit); writer.Write("')"); return item; }
public Network(int inputsCount, int layersCount, List<int> neuronsCountInHiddenLayers, Functions.IActivationFunction function, Neurons.INeuronInitilizer initializer ) { NetworkInit(inputsCount, layersCount); if (neuronsCountInHiddenLayers.Count != layersCount) throw new ApplicationException("Number of layers and provided layer's neuron count do not match!"); layers[0] = new Layer(inputsCount, inputsCount, function, initializer); for(int i = 1; i < layers.Length; i++) layers[i] = new Layer(neuronsCountInHiddenLayers[i-1], neuronsCountInHiddenLayers[i], function, initializer); }
public Layer(int inputsCount, int neuronsCount, Functions.IActivationFunction function, INeuronInitilizer initializer) { Inputs = inputsCount; neurons = new Neuron[neuronsCount]; for(int i = 0; i < neuronsCount; ++i) { neurons[i] = new Neuron(inputsCount, function, initializer); } Output = new double[neuronsCount]; }
private static void AddFunction(UserType type, Functions function) { if (!_functionMap.ContainsKey(type)) { _functionMap.Add(type, new List<Functions>()); } if (!_functionMap[type].Contains(function)) { _functionMap[type].Add(function); } }
public Button GetButton(Functions funcName) { var fields = _element.GetFields(typeof(IButton)); if (fields.Count == 1) return (Button) fields[0].GetValue(_element); var buttons = fields.Select(f => (Button) f.GetValue(_element)).ToList(); var button = buttons.FirstOrDefault(b => b.Function.Equals(funcName)); if (button != null) return button; var name = funcName.ToString(); button = buttons.FirstOrDefault(b => NamesEqual(ToButton(b.Name), ToButton(name))); if (button == null) throw Exception($"Can't find button '{name}' for Element '{ToString()}'"); return button; }
private void TryToCallTesting(Functions invokingMethod) { if (invokingMethod == callOnMethod) { if (methodToCall == Method.Pass) { IntegrationTest.Pass(gameObject); } else { IntegrationTest.Fail(gameObject); } afterFrames = 0; afterSeconds = 0.0f; startTime = float.PositiveInfinity; startFrame = int.MinValue; } }
public BillboardSystem(GraphicsDevice graphicsDevice, Functions.AssetHolder assets, Texture2D texture, Vector2 billboardSize, Vector3[] positions) { this.positions = positions; this.nBillboards = positions.Length; this.billboardSize = billboardSize; this.graphicsDevice = graphicsDevice; this.texture = texture; greenCircle = assets.Load<Texture2D>("circle"); effect = assets.Load<Effect>("billboardingeffect"); Random r = new Random(); generateBillBoard(positions); }
public ActionResult Mail(FormCollection form) { Functions f = new Functions(); string message = "Someone did something wrong"; if (form.AllKeys.Count() > 3) { message = "Name: " + form["name"].ToString() + "\nEmail: " + form["email"].ToString() + "\nWebsite: " + form["website"].ToString() + "\n\nMessage:\n" + form["message"].ToString(); } f.SendEmail(message, Constants.ContactUsEmail, "Netintercom [Web Request]"); return RedirectToAction("Index"); }
private async void setup() { Functions functions = new Functions(); JsonValue list = await functions.getWorkshopSets (); JsonValue results = list ["Results"]; tableItems = new List<WorkshopSet>(); List<WorkshopSet> sets = deserialise (results); int j = 0; for (int i = 0; i < sets.Count; i++) { if (sets [i].Archived == null) { tableItems.Add(sets [i]); j++; } } this.TableView.ReloadData (); }
public Database(string typeName, string server, string name, string connectionString) { this.typeName = typeName; this.server = server; this.name = name; this.connectionString = connectionString; connection = new OdbcConnection(this.connectionString); _tables = new Tables(this); _views = new Views(this); _sequences = new Sequences(this); _storedprocedures = new StoredProcedures(this); _functions = new Functions(this); _modules = new Modules(this); _mqts = new MQTS(this); }
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments) { PictureRepository picRep = new PictureRepository(); Functions functions = new Functions(); // The Name of the Upload component is "attachments" int NewPicID = picRep.GetLastPictureId(Convert.ToInt32(HttpContext.Session["ClientId"])); NewPicID++; Picture ins = new Picture(); foreach (var file in attachments) { // Some browsers send file names with full path. This needs to be stripped. var fileName = Path.GetFileName(file.FileName); var extention = fileName.Substring(fileName.IndexOf('.')); var newfilename = NewPicID.ToString() + extention; // Check if Path exsits string serverpath = Server.MapPath("~/Images/Client/" + HttpContext.Session["ClientId"].ToString() + "/Ads"); if (!Directory.Exists(serverpath)) { Directory.CreateDirectory(serverpath); } var physicalPath = Path.Combine(Server.MapPath("~/Images/Client/" + HttpContext.Session["ClientId"].ToString() + "/Ads"), newfilename); //...Resize.. Image original = Image.FromStream(file.InputStream, true, true); Image resized = functions.ResizeImage(original, new Size(500, 500)); resized.Save(physicalPath, ImageFormat.Jpeg); string finalpath = physicalPath.ToString(); finalpath = finalpath.Substring(finalpath.IndexOf("Images")); finalpath = finalpath.Replace('\\', '/'); //...Save In DB... ins.PicUrl = Constants.HTTPPath + finalpath; ins.ClientId = Convert.ToInt32(HttpContext.Session["ClientId"]); ins = picRep.InsertPicture(ins); } // Return an empty string to signify success if (ins.PictureId != 0) return Json(new { status = ins.PictureId.ToString() }, "text/plain"); else return Json(new { status = "0" }, "text/plain"); }
private async Task<Manager> Modify(Functions func, string name, Memory memory) { Object data; switch (func) { case Functions.Add: await manager.ModifyMemory (Manager.Command.Add, name, memory); break; case Functions.Remove: await manager.ModifyMemory (Manager.Command.Remove, name, memory); break; case Functions.Replace: await manager.ModifyMemory (Manager.Command.Replace, name, memory); break; case Functions.Get: await manager.ModifyMemory (Manager.Command.Retrieve, name, memory); break; } return null; }
public Invoke(int function, int[] arguments) { this.function = function; this.arguments = arguments; var functions = new Functions(); int x = arguments[0]; var unwrappedX = (IntConstant)ConstantFactory.GetConstant(x); int y = arguments[1]; var unwrappedY = (IntConstant)ConstantFactory.GetConstant(y); var func = functions.IdToFunction[this.function]; var result = func.Invoke(unwrappedX.value, unwrappedY.value); var constant = new ConstantFactory().CreateIntOrBool(result); this.id = constant.id; }
public void getGift() { StringBuilder sb = new StringBuilder(); Hashtable[] gifts; gifts = myFunctions.giftGet(18); moyu.Functions myFunction = new Functions(); foreach (Hashtable gift in gifts) { try { string number = gift["message"].ToString().Split(new char[3] { '|', '|', '|' })[0]; sb.Append("<li>" + gift["message"].ToString().Substring(0, 3) + "**" + number.Substring(number.Length - 2, 2) + "在<span>" + myFunction.kindTime(Convert.ToDateTime(gift["date"])) + "</span>获得了"); sb.Append(gift["gift"]); sb.Append("</li>"); } catch { } } Response.Write(sb); }
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments) { Functions functions = new Functions(); Documents ins = new Documents(); // The Name of the Upload component is "attachments" foreach (var file in attachments) { // Some browsers send file names with full path. This needs to be stripped. var fileName = Path.GetFileName(file.FileName); // Check if Path exsits string serverpath = Server.MapPath("~/Images/Client/" + HttpContext.Session["ClientId"].ToString() + "/Docs"); if (!Directory.Exists(serverpath)) { Directory.CreateDirectory(serverpath); } var physicalPath = Path.Combine(Server.MapPath("~/Images/Client/" + HttpContext.Session["ClientId"].ToString() + "/Docs"), fileName); file.SaveAs(physicalPath); string finalpath = physicalPath.ToString(); finalpath = finalpath.Substring(finalpath.IndexOf("Images")); finalpath = finalpath.Replace('\\', '/'); //...Save In DB... ins.DocumentName = fileName; ins.ClientId = Convert.ToInt32(HttpContext.Session["ClientId"]); ins.PathUrl = Constants.HTTPPath + finalpath; ins = DocRep.AddDocument(ins); } // Return an empty string to signify success if (ins.DocId != 0) return Json(new { status = ins.DocId.ToString() }, "text/plain"); else return Json(new { status = "0" }, "text/plain"); }
public MLMVN(MainWindow function) { window = function; functions = new Functions(function); }
/// <summary> /// Initializes a new instance of the <see cref="Hd44780LcdConnection" /> class. /// </summary> /// <param name="settings">The settings.</param> /// <param name="pins">The pins.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// dataPins;There must be either 4 or 8 data pins /// or /// settings;ScreenHeight must be between 1 and 4 rows /// or /// settings;PatternWidth must be 5 pixels /// or /// settings;PatternWidth must be either 7 or 10 pixels height /// </exception> /// <exception cref="System.ArgumentException"> /// At most 80 characters are allowed /// or /// 10 pixels height pattern cannot be used with 2 rows /// </exception> public Hd44780LcdConnection(Hd44780LcdConnectionSettings settings, Hd44780Pins pins) { settings = settings ?? new Hd44780LcdConnectionSettings(); this.pins = pins; if (pins.Data.Length != 4 && pins.Data.Length != 8) throw new ArgumentOutOfRangeException("pins", pins.Data.Length, "There must be either 4 or 8 data pins"); width = settings.ScreenWidth; height = settings.ScreenHeight; if (height < 1 || height > MAX_HEIGHT) throw new ArgumentOutOfRangeException("settings", height, "ScreenHeight must be between 1 and 4 rows"); if (width * height > MAX_CHAR) throw new ArgumentException("At most 80 characters are allowed"); if (settings.PatternWidth != 5) throw new ArgumentOutOfRangeException("settings", settings.PatternWidth, "PatternWidth must be 5 pixels"); if (settings.PatternHeight != 8 && settings.PatternHeight != 10) throw new ArgumentOutOfRangeException("settings", settings.PatternWidth, "PatternWidth must be either 7 or 10 pixels height"); if (settings.PatternHeight == 10 && (height % 2) == 0) throw new ArgumentException("10 pixels height pattern cannot be used with an even number of rows"); functions = (settings.PatternHeight == 8 ? Functions.Matrix5x8 : Functions.Matrix5x10) | (height == 1 ? Functions.OneLine : Functions.TwoLines) | (pins.Data.Length == 4 ? Functions.Data4bits : Functions.Data8bits); entryModeFlags = /*settings.RightToLeft ? EntryModeFlags.EntryRight | EntryModeFlags.EntryShiftDecrement :*/ EntryModeFlags.EntryLeft | EntryModeFlags.EntryShiftDecrement; encoding = settings.Encoding; BacklightEnabled = false; if (pins.ReadWrite != null) pins.ReadWrite.Write(false); pins.RegisterSelect.Write(false); pins.Clock.Write(false); foreach (var dataPin in pins.Data) dataPin.Write(false); WriteByte(0x33, false); // Initialize WriteByte(0x32, false); WriteCommand(Command.SetFunctions, (int) functions); WriteCommand(Command.SetDisplayFlags, (int) displayFlags); WriteCommand(Command.SetEntryModeFlags, (int) entryModeFlags); Clear(); BacklightEnabled = true; }
/// <summary> /// Use this method to load a new texture. This can be used for a first time but also to load a new texture later on. /// </summary> /// <param name="assets">The contentmanager.</param> /// <param name="key">The path to the key in your content porject.</param> /// <param name="frameCount">The amount of frames the spritesheet consists of.</param> /// <param name="framesPerSec">How many frames you want to show per second.</param> public void Load(Functions.AssetHolder assets, string key, int frameCount, int framesPerSec) { framecount = frameCount; myTexture = assets.Load<Texture2D>(key); this.Origin = new Vector2(this.myTexture.Width / (2 * framecount), this.myTexture.Height / 2); timePerFrame = (float)1 / framesPerSec; Frame = 0; totalElapsed = 0; paused = false; }
public string FormatReplication() { if (DataScriptSize <= 0) { return(String.Empty); } var replicatedObjects = new List <IUnrealNetObject>(); if (Variables != null) { replicatedObjects.AddRange(Variables.Where(prop => prop.HasPropertyFlag(Flags.PropertyFlagsLO.Net) && prop.RepOffset != ushort.MaxValue)); } if (Package.Version < VReliableDeprecation && Functions != null) { replicatedObjects.AddRange(Functions.Where(func => func.HasFunctionFlag(Flags.FunctionFlags.Net) && func.RepOffset != ushort.MaxValue)); } if (replicatedObjects.Count == 0) { return(String.Empty); } var statements = new Dictionary <uint, List <IUnrealNetObject> >(); replicatedObjects.Sort((ro, ro2) => ro.RepKey.CompareTo(ro2.RepKey)); for (int netIndex = 0; netIndex < replicatedObjects.Count; ++netIndex) { var firstObject = replicatedObjects[netIndex]; var netObjects = new List <IUnrealNetObject> { firstObject }; for (int nextIndex = netIndex + 1; nextIndex < replicatedObjects.Count; ++nextIndex) { var nextObject = replicatedObjects[nextIndex]; if (nextObject.RepOffset != firstObject.RepOffset || nextObject.RepReliable != firstObject.RepReliable ) { netIndex = nextIndex - 1; break; } netObjects.Add(nextObject); } netObjects.Sort((o, o2) => String.Compare(o.Name, o2.Name, StringComparison.Ordinal)); if (!statements.ContainsKey(firstObject.RepKey)) { statements.Add(firstObject.RepKey, netObjects); } } replicatedObjects.Clear(); var output = "\r\nreplication" + UnrealConfig.PrintBeginBracket(); UDecompilingState.AddTab(); foreach (var statement in statements) { try { var pos = (ushort)(statement.Key & 0x0000FFFF); var rel = Convert.ToBoolean(statement.Key & 0xFFFF0000); output += "\r\n" + UDecompilingState.Tabs; if (!UnrealConfig.SuppressComments) { output += String.Format("// Pos:0x{0:X3}\r\n{1}", pos, UDecompilingState.Tabs); } ByteCodeManager.Deserialize(); ByteCodeManager.JumpTo(pos); string statementCode; try { statementCode = ByteCodeManager.CurrentToken.Decompile(); } catch (Exception e) { statementCode = String.Format("/* An exception occurred while decompiling condition ({0}) */", e); } var statementType = Package.Version < VReliableDeprecation ? rel ? "reliable " : "unreliable " : String.Empty; var statementFormat = String.Format("{0}if({1})", statementType, statementCode); output += statementFormat; UDecompilingState.AddTab(); // NetObjects for (int i = 0; i < statement.Value.Count; ++i) { var shouldSplit = i % 2 == 0; if (shouldSplit) { output += "\r\n" + UDecompilingState.Tabs; } var netObject = statement.Value[i]; output += netObject.Name; var isNotLast = i != statement.Value.Count - 1; if (isNotLast) { output += ", "; } } UDecompilingState.RemoveTab(); // IsNotLast if (statements.Last().Key != statement.Key) { output += "\r\n"; } } catch (Exception e) { output += String.Format("/* An exception occurred while decompiling an statement! ({0}) */", e); } } UDecompilingState.RemoveTab(); return(output + UnrealConfig.PrintEndBracket() + "\r\n"); }
public static Vector3 GetSpotlightPosition(this Vehicle vehicle) => Functions.GetSpotlightPosition(vehicle);
public bool RemoveSchoolPictures(int ClientId) { bool Removed = true; //...Get User and Date Data... string strTrx = "Remove_Picture"; //...Database Connection... DataBaseConnection dbConn = new DataBaseConnection(); SqlConnection con = dbConn.SqlConn(); con.Open(); //...Command Interface... SqlCommand cmdI = con.CreateCommand(); SqlTransaction trx; trx = con.BeginTransaction(strTrx); cmdI.Connection = con; cmdI.Transaction = trx; try { //...Insert Record... cmdI.Parameters.Clear(); cmdI.CommandText = "f_Admin_Remove_Picture_Per_School"; //cmdI.Connection.Open(); cmdI.CommandType = System.Data.CommandType.StoredProcedure; cmdI.Parameters.AddWithValue("@ClientId", ClientId); // int //...Return new ID... int ret = (int)cmdI.ExecuteScalar(); //...Commit Transaction... trx.Commit(); cmdI.Connection.Close(); } catch (SqlException ex) { if (trx != null) { trx.Rollback(); Removed = false; } //...Save Error to Log... Functions func = new Functions(); func.LogError(ex.ToString()); } finally { //...Check for close and respond accordingly.. if (con.State != ConnectionState.Closed) { con.Close(); } //...Clean up... con.Dispose(); cmdI.Dispose(); trx.Dispose(); } return Removed; }
protected virtual void HealTarget() { if (!Target.IsAttackTarget(this) || Target.Race == ObjectType.Player) { Target = null; return; } ShockTime = 0; bool ranged = CurrentLocation == Target.CurrentLocation || !Functions.InRange(CurrentLocation, Target.CurrentLocation, 1); if (ranged) { Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation); Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, TargetID = Target.ObjectID }); ActionTime = Envir.Time + 300; AttackTime = Envir.Time + AttackSpeed + 300; Target.HealAmount += MaxSC; Broadcast(new S.ObjectEffect { ObjectID = Target.ObjectID, Effect = SpellEffect.Healing }); SearchTarget(); } if (Target.Dead || Target.PercentHealth == 100 || (Target.Race == ObjectType.Player && Functions.MaxDistance(CurrentLocation, Target.CurrentLocation) > 3)) { SearchTarget(); } }
/// <summary> /// Tests the express where-clause specified in param 'clause' /// </summary> /// <param name="clause">The express clause to test</param> /// <returns>true if the clause is satisfied.</returns> public bool ValidateClause(IfcCondenserClause clause) { var retVal = false; try { switch (clause) { case IfcCondenserClause.CorrectPredefinedType: retVal = !(Functions.EXISTS(PredefinedType)) || (PredefinedType != IfcCondenserTypeEnum.USERDEFINED) || ((PredefinedType == IfcCondenserTypeEnum.USERDEFINED) && Functions.EXISTS(this /* as IfcObject*/.ObjectType)); break; case IfcCondenserClause.CorrectTypeAssigned: retVal = (Functions.SIZEOF(IsTypedBy) == 0) || (Functions.TYPEOF(this /* as IfcObject*/.IsTypedBy.ItemAt(0).RelatingType).Contains("IFC4.IFCCONDENSERTYPE")); break; } } catch (Exception ex) { var log = Validation.ValidationLogging.CreateLogger <Xbim.Ifc4.HvacDomain.IfcCondenser>(); log?.LogError(string.Format("Exception thrown evaluating where-clause 'IfcCondenser.{0}' for #{1}.", clause, EntityLabel), ex); } return(retVal); }
public JsonResult AddProductGallery() { var _result = new Result(); try { var LogoImgPath = new List <string>(); if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var keys = System.Web.HttpContext.Current.Request.Files.AllKeys; foreach (var key in keys) { var pic = System.Web.HttpContext.Current.Request.Files[key]; var _fileName = Functions.PhotoTitle(pic.FileName.Split('.')[0]); var _fileExtension = Path.GetExtension(pic.FileName); var images = _fileName + _fileExtension; var img = Image.FromStream(pic.InputStream); string path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(@"/UploadFile/Galeri"), images); Functions.CropImage(img, path, 2000, 1100, false, 1); // give the image width and height //last parameter cases /// 1- only resize width/height ratio /// 4- only resize transparent pictures by width/height ratio // IF U WANNA CROP AND RESIZE THE PICTURE GIVE THE 3RD PARAMETER TRUE GC.Collect(); LogoImgPath.Add(images); } //using (Entities db = new Entities()) need entity connection //{ // foreach (var item in LogoImgPath) // { // var newItem = new Gallery() // { // PhotoPath = item // }; // db.Gallery.Add(newItem); // } // db.SaveChanges(); // _result.Success = true; //} } else { _result.Success = false; _result.Message = "Fotoğraf Seçiniz"; } } catch (Exception) { _result.Success = false; _result.Message = "Bir Hata Oluştu.Lütfen Tekrar Deneyin"; } return(Json(_result)); }
public void SendPartyChatServerMessage(string content, int senderId, string senderName) { Send(new ChatServerMessage(4, content, Functions.ReturnUnixTimeStamp(DateTime.Now), "", senderId, senderName)); }
static void TestMomentum(RelativisticParticle particle) { Assert.AreEqual(particle.Momentum.InvariantScalar, -Functions.Pow(particle.Mass, 2), "Momentum scalar product"); }
private void SENDSTRING(SplusExecutionContext __context__, CrestronString SCMD) { __context__.SourceCodeLine = 164; MakeString(ROLAND_TXD__DOLLAR__, "{0}{1};", Functions.Chr(2), SCMD); }
private void FillContent() { BeginUpdate(); try { ListViewItem[] lvis = new ListViewItem[thisContent.Folders.Count + thisContent.Files.Count]; int k = 0; ArrayList hiddenitem = new ArrayList(); for (int i = 0; i < thisContent.Folders.Count; i++) { lvis[k] = new ListViewItem(thisContent.Folders[i].Name, thisContent.Folders[i].IconIndex); lvis[k].SubItems.Add(thisContent.Folders[i].FolderType == CommVar.FolderType.ExtractFolder ? "Extract File Folder" : "File Folder"); lvis[k].SubItems.Add(Functions.SizeStr(thisContent.Folders[i].Size)).Tag = thisContent.Folders[i].Size; lvis[k].Tag = thisContent.Folders[i]; if (thisContent.Folders[i].Hidden) { hiddenitem.Add(i); } k++; } for (int j = 0; j < thisContent.Files.Count; j++) { if (thisContent.Files[j].SpecialItem) { continue; } int iconindex = -1; switch (thisContent.Files[j].Extension.ToLower()) { case ".htm": iconindex = CommVar.HtmIconIndex; break; case ".html": iconindex = CommVar.HtmlIconIndex; break; case ".mht": iconindex = CommVar.MhtIconIndex; break; case ".xml": iconindex = CommVar.XmlIconIndex; break; default: iconindex = thisContent.Files[j].IconIndex; break; } lvis[k] = new ListViewItem(thisContent.Files[j].Name, iconindex); lvis[k].SubItems.Add(thisContent.Files[j].Type); lvis[k].SubItems.Add(Functions.SizeStr(thisContent.Files[j].Size)).Tag = thisContent.Files[j].Size; lvis[k].Tag = thisContent.Files[j]; if (thisContent.Files[j].Path != "") { lvis[k].Name = thisContent.Files[j].Path; } if (thisContent.Files[j].Hidden) { hiddenitem.Add(thisContent.Folders.Count + j); } k++; } Array.Resize(ref lvis, k); Items.AddRange(lvis); if (HighlightItem != -1) { Items[HighlightItem].EnsureVisible(); Items[HighlightItem].Selected = true; HighlightItem = -1; } OnListViewFilled(this, new FillListViewEventArgs(hiddenitem)); } catch { } EndUpdate(); }
/// <summary> /// 绑定数据到列表 /// </summary> /// <param name="selNum">数据条数</param> /// <param name="sqlWhereAndOrderBy">条件</param> protected override void BindLVData(int selNum = 0, string sqlWhereAndOrderBy = null) { this.lvContent.BeginUpdate(); this.lvContent.Items.Clear(); try { if (selNum <= 0) { selNum = this.DefaultPageSize; } if (string.IsNullOrEmpty(sqlWhereAndOrderBy) || sqlWhereAndOrderBy.Equals("")) { sqlWhereAndOrderBy = "1=1"; } this.CurrentSqlWhere = sqlWhereAndOrderBy; IList <Card> listData = null; IDAL.ICard objDAL = DALFactory.DALFactory.Card(); listData = objDAL.GetListByWhere(selNum, sqlWhereAndOrderBy); if (!(listData == null || listData.Count <= 0)) { foreach (Card model in listData) { //序号,50|卡号,80|卡片类型,70|小区编码,60|楼栋编码,60|单元编码,60|房间编码,80|卡片系列号,210|卡片有效期,100|发卡时间,100|持卡者姓名,100|联系电话,100|所在房间,100|所在单元,100|所在楼栋,100|所在小区,120 ListViewItem item = new ListViewItem(new string[] { Convert.ToString(lvContent.Items.Count + 1), model.CardNo.ToString(), model.CardTypeDesc, FormatBuildingCode(model.RAreaCode), FormatBuildingCode(model.RBuildCode), FormatBuildingCode(model.RUnitCode), FormatRoomCode(model.RRoomCode), model.SerialNo, Functions.ConvertToNormalTime(model.ExpiryDate).ToString(Config.TimeFormat), Functions.ConvertToNormalTime(model.CreateDate).ToString(Config.TimeFormat), model.Contact, model.Tel, model.RoomName, model.UnitName, model.BuildName, model.AreaName }) { Tag = model, Font = new Font("宋体", 9, FontStyle.Regular) }; this.lvContent.Items.Add(item); } } } catch (Exception err) { CMessageBox.ShowWaring(string.Format("系统错误,错误如下:\r\n{0}!", err.Message), Config.DialogTitle); } this.lvContent.EndUpdate(); }
public static void SetSpotlightRotation(this Vehicle vehicle, Quaternion rotation) => Functions.SetSpotlightRotation(vehicle, rotation);
protected override bool InAttackRange() { return CurrentMap == Target.CurrentMap && Functions.InRange(CurrentLocation, Target.CurrentLocation, Globals.DataRange); }
public static bool IsSpotlightInSearchMode(this Vehicle vehicle) => Functions.IsSpotlightInSearchMode(vehicle);
public override void ProcessSearch() { if (!CanMove || SEnvir.Now < SearchTime) { return; } int bestDistance = int.MaxValue; List <ItemObject> closest = new List <ItemObject>(); foreach (MapObject ob in CompanionOwner.VisibleObjects) { if (ob.Race != ObjectType.Item) { continue; } int distance = Functions.Distance(ob.CurrentLocation, CurrentLocation); if (distance > ViewRange) { continue; } if (distance > bestDistance) { continue; } ItemObject item = (ItemObject)ob; if (item.Account != CompanionOwner.Character.Account || !item.MonsterDrop) { continue; } long amount = 0; if (item.Item.Info.Effect == ItemEffect.Gold && item.Account.GuildMember != null && item.Account.GuildMember.Guild.GuildTax > 0) { amount = (long)Math.Ceiling(item.Item.Count * item.Account.GuildMember.Guild.GuildTax); } ItemCheck check = new ItemCheck(item.Item, item.Item.Count - amount, item.Item.Flags, item.Item.ExpireTime); if (!CanGainItems(true, check)) { continue; } if (distance != bestDistance) { closest.Clear(); } closest.Add(item); bestDistance = distance; } if (closest.Count == 0) { SearchTime = SEnvir.Now.AddSeconds(10); return; } TargetItem = closest[SEnvir.Random.Next(closest.Count)]; }
void OnGUI() { if (Provider.isConnected && !Provider.isLoading) { if (MenuGUI.instance.claimflagEspEnabled) { for (int i = 0; i < ESPUtil.claimflags.Length; i++) { if (ESPUtil.claimflags[i] != null) { Vector3 pos = ESPUtil.mainCamera.WorldToScreenPoint(ESPUtil.claimflags[i].transform.position); pos.y = Screen.height - pos.y; if (pos.z >= 0) { string labelText = ""; float claimflagDistance = Functions.GetDistance(ESPUtil.claimflags[i].transform.position); if (claimflagDistance < MenuGUI.instance.claimflagEspMaxDistance && Functions.IsVisable(ESPUtil.claimflags[i].transform)) { if (MenuGUI.instance.claimflagDistance) { if (MenuGUI.instance.claimflagDistance) { labelText += "<color=#F8F8FF>[</color>" + claimflagDistance.ToString() + "<color=#F8F8FF>] </color>"; } } if (MenuGUI.instance.claimflagName) { labelText += "Claim Flag"; } Functions.DrawLabel(labelText, MenuGUI.instance.claimflagLabelColor, pos); if (MenuGUI.instance.claimflag3DBoxes) { Functions.Draw3DBox(ESPUtil.claimflags[i].gameObject.GetComponent <Collider>().bounds, MenuGUI.instance.claimflag3DBoxColor); } } } } } } } }
protected void btnSave_Click(object sender, EventArgs e) { int err = 0; try { DateTime sdt = DateTime.Parse(ddlyear2.SelectedValue + "/" + ddlmonth2.SelectedValue + "/" + ddlday2.SelectedValue); } catch { err = 1; } if (err == 0) { if (ddlstandard.SelectedIndex > 0) { string strsql = "select intid from tblstudentattendance where dtdate='" + ddlyear2.SelectedValue + "/" + ddlmonth2.SelectedValue + "/" + ddlday2.SelectedValue + "' and strclass='" + ddlstandard.SelectedValue + "' and intschool=" + Session["SchoolID"].ToString() + ""; DataSet ds2 = new DataSet(); DataAccess da2 = new DataAccess(); ds2 = da2.ExceuteSql(strsql); if (ds2.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds2.Tables[0].Rows.Count; i++) { Functions.UserLogs(Session["UserID"].ToString(), "tblstudentattendance", ds2.Tables[0].Rows[i]["intid"].ToString(), "Deleted", Session["PatronType"].ToString(), Session["SchoolID"].ToString(), 57); } } da = new DataAccess(); string str = "delete tblstudentattendance where dtdate='" + ddlyear2.SelectedValue + "/" + ddlmonth2.SelectedValue + "/" + ddlday2.SelectedValue + "' and strclass='" + ddlstandard.SelectedValue + "' and intschool=" + Session["SchoolID"].ToString() + ""; da.ExceuteSqlQuery(str); foreach (DataGridItem dgit in dgstudentattend.Items) { DataRowView drd = (DataRowView)dgit.DataItem; RadioButton rbtnpresent = (RadioButton)dgit.FindControl("rbtnpresent"); RadioButton rbtnabsent = (RadioButton)dgit.FindControl("rbtnabsent"); TextBox txtreason = (TextBox)dgit.FindControl("txtreason"); DropDownList ddlsession = (DropDownList)dgit.FindControl("ddlseasion"); if (rbtnabsent.Checked) { SqlCommand RegCommand; SqlConnection Conn = new SqlConnection(ConfigurationManager.AppSettings["conn"]); Conn.Open(); RegCommand = new SqlCommand("spstudentattendance", Conn); RegCommand.CommandType = CommandType.StoredProcedure; RegCommand.Parameters.Add("@intID", "0"); RegCommand.Parameters.Add("@intschool", Session["SchoolID"].ToString()); RegCommand.Parameters.Add("@intstaff", Session["UserID"].ToString()); RegCommand.Parameters.Add("@strclass", ddlstandard.SelectedValue); RegCommand.Parameters.Add("@intstudent", dgit.Cells[0].Text); RegCommand.Parameters.Add("@dtdate", ddlyear2.SelectedValue + "/" + ddlmonth2.SelectedValue + "/" + ddlday2.SelectedValue); RegCommand.Parameters.Add("@strsession", ddlsession.SelectedValue); RegCommand.Parameters.Add("@strclassteacher", lblhometeacher.Text); RegCommand.Parameters.Add("@strreason", txtreason.Text.Trim()); RegCommand.ExecuteNonQuery(); Conn.Close(); } } //Response.Redirect("studentattendance.aspx"); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "redirect script", "alert('Details Saved Successfully!'); location.href='studentattendance.aspx';", true); } else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Please Select Class')", true); } } else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Invalid Date')", true); } }
protected override bool InAttackRange() { return(CurrentMap == Target.CurrentMap && Functions.InRange(CurrentLocation, Target.CurrentLocation, HealRange)); }
/// <summary> /// Faz a leitura do XML de pedido de consulta da situação da NFe /// </summary> /// <param name="cArquivoXML">Nome do XML a ser lido</param> /// <by>Wandrey Mundin Ferreira</by> /// protected override void PedSit(int emp, DadosPedSit dadosPedSit) { dadosPedSit.tpAmb = Empresas.Configuracoes[emp].AmbienteCodigo; dadosPedSit.chNFe = string.Empty; dadosPedSit.tpEmis = Empresas.Configuracoes[emp].tpEmis; dadosPedSit.versao = "";// NFe.ConvertTxt.versoes.VersaoXMLPedSit; if (Path.GetExtension(this.NomeArquivoXML).ToLower() == ".txt") { // tpAmb|2 // tpEmis|1 <<< opcional >>> // chNFe|35080600000000000000550000000000010000000000 // versao|3.10 List <string> cLinhas = Functions.LerArquivo(this.NomeArquivoXML); Functions.PopulateClasse(dadosPedSit, cLinhas); if (dadosPedSit.versao == "2.00") { dadosPedSit.versao = "2.01"; } } else { bool doSave = false; XmlDocument doc = new XmlDocument(); doc.Load(this.NomeArquivoXML); XmlNodeList consSitNFeList = doc.GetElementsByTagName("consSitNFe"); foreach (XmlNode consSitNFeNode in consSitNFeList) { XmlElement consSitNFeElemento = (XmlElement)consSitNFeNode; dadosPedSit.tpAmb = Convert.ToInt32("0" + consSitNFeElemento.GetElementsByTagName(TpcnResources.tpAmb.ToString())[0].InnerText); dadosPedSit.chNFe = consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0].InnerText; dadosPedSit.versao = consSitNFeElemento.Attributes[NFe.Components.TpcnResources.versao.ToString()].Value; dadosPedSit.mod = dadosPedSit.chNFe.Substring(20, 2); //Se alguém ainda gerar com a versão 2.00 vou mudar para a "2.01" para facilitar para o usuário do UniNFe if (dadosPedSit.versao == "2.00") { consSitNFeElemento.Attributes[NFe.Components.TpcnResources.versao.ToString()].InnerText = dadosPedSit.versao = "2.01"; doSave = true; } if (consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString()).Count != 0) { this.dadosPedSit.tpEmis = Convert.ToInt16(consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0].InnerText); /// para que o validador não rejeite, excluo a tag <tpEmis> doc.DocumentElement.RemoveChild(consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0]); /// salvo o arquivo modificado doSave = true; } } if (doSave) { doc.Save(this.NomeArquivoXML); } } if (this.dadosPedSit.versao == "") { throw new Exception(NFeStrConstants.versaoError); } }
private void BtnBack_Click(object sender, RoutedEventArgs e) { Functions.AddTextToTextBox(GameState.GamePage.TxtGame, TxtGuild.Text.Trim()); GameState.GoBack(); }
/// <summary> /// Ler o retorno da consulta situação da nota fiscal e de acordo com o status ele trata as notas enviadas se ainda não foram tratadas /// </summary> /// <param name="ChaveNFe">Chave da NFe que está sendo consultada</param> /// <remarks> /// Autor: Wandrey Mundin Ferreira /// Data: 16/06/2010 /// </remarks> private void LerRetornoSitNFe(string ChaveNFe) { int emp = Empresas.FindEmpresaByThread(); oGerarXML.XmlDistEvento(emp, this.vStrXmlRetorno); //<<<danasa 6-2011 LerXML oLerXml = new LerXML(); MemoryStream msXml = Functions.StringXmlToStreamUTF8(this.vStrXmlRetorno); FluxoNfe oFluxoNfe = new FluxoNfe(); XmlDocument doc = new XmlDocument(); doc.Load(msXml); XmlNodeList retConsSitList = doc.GetElementsByTagName("retConsSitNFe"); foreach (XmlNode retConsSitNode in retConsSitList) { XmlElement retConsSitElemento = (XmlElement)retConsSitNode; //Definir a chave da NFe a ser pesquisada string strChaveNFe = "NFe" + ChaveNFe; //Definir o nome do arquivo da NFe e seu caminho string strNomeArqNfe = oFluxoNfe.LerTag(strChaveNFe, FluxoNfe.ElementoFixo.ArqNFe); if (string.IsNullOrEmpty(strNomeArqNfe)) { //if (string.IsNullOrEmpty(strChaveNFe)) // throw new Exception("LerRetornoSitNFe(): Não pode obter o nome do arquivo"); strNomeArqNfe = strChaveNFe.Substring(3) + Propriedade.ExtEnvio.Nfe; } string strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqNfe; #region CNPJ da chave não é de uma empresa Uninfe bool notDaEmpresa = (ChaveNFe.Substring(6, 14) != Empresas.Configuracoes[emp].CNPJ || ChaveNFe.Substring(0, 2) != Empresas.Configuracoes[emp].UnidadeFederativaCodigo.ToString()); /* * if (File.Exists(strArquivoNFe)) * { * if (notDaEmpresa) * throw new Exception("NFe gravada na pasta 'EmProcessamento' não tem seu CNPJ igual ao da empresa sendo processada"); * } * else * { * if (notDaEmpresa) * return; * }*/ if (!File.Exists(strArquivoNFe)) { if (notDaEmpresa) { return; } } #endregion //Pegar o status de retorno da NFe que está sendo consultada a situação var cStatCons = string.Empty; if (retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0] != null) { cStatCons = retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText; } switch (cStatCons) { #region Rejeições do XML de consulta da situação da NFe (Não é a nfe que foi rejeitada e sim o XML de consulta da situação da nfe) #region Validação do Certificado de Transmissão case "280": case "281": case "283": case "286": case "284": case "285": case "282": #endregion #region Validação Inicial da Mensagem no WebService case "214": case "243": case "108": case "109": #endregion #region Validação das informações de controle da chamada ao WebService case "242": case "409": case "410": case "411": case "238": case "239": #endregion #region Validação da forma da área de dados case "215": case "516": case "517": case "545": case "587": case "588": case "404": case "402": #endregion #region Validação das regras de negócios da consulta a NF-e case "252": case "226": case "236": case "614": case "615": case "616": case "617": case "618": case "619": case "620": break; #endregion #region Nota fiscal rejeitada case "217": //J-NFe não existe na base de dados do SEFAZ goto case "TirarFluxo"; case "562": //J-Verificar se o campo "Código Numérico" informado na chave de acesso é diferente do existente no BD goto case "TirarFluxo"; case "561": //J-Verificar se campo MM (mês) informado na Chave de Acesso é diferente do existente no BD goto case "TirarFluxo"; #endregion #endregion #region Nota fiscal autorizada case "100": //Autorizado o uso da NFe case "150": //Autorizado o uso da NFe fora do prazo XmlNodeList infConsSitList = retConsSitElemento.GetElementsByTagName("infProt"); if (infConsSitList != null) { foreach (XmlNode infConsSitNode in infConsSitList) { XmlElement infConsSitElemento = (XmlElement)infConsSitNode; //Pegar o Status do Retorno da consulta situação string strStat = Functions.LerTag(infConsSitElemento, NFe.Components.TpcnResources.cStat.ToString(), false); //Pegar a versão do XML var protNFeElemento = (XmlElement)retConsSitElemento.GetElementsByTagName("protNFe")[0]; string versao = protNFeElemento.GetAttribute(NFe.Components.TpcnResources.versao.ToString()); switch (strStat) { case "100": //NFe Autorizada case "150": //NFe Autorizada fora do prazo string strProtNfe = retConsSitElemento.GetElementsByTagName("protNFe")[0].OuterXml; //Definir o nome do arquivo -procNfe.xml string strArquivoNFeProc = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(strArquivoNFe, Propriedade.ExtEnvio.Nfe) + Propriedade.ExtRetorno.ProcNFe; //Se existir o strArquivoNfe, tem como eu fazer alguma coisa, se ele não existir //Não tenho como fazer mais nada. Wandrey 08/10/2009 if (File.Exists(strArquivoNFe)) { //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados oLerXml.Nfe(strArquivoNFe); //Verificar se a -nfe.xml existe na pasta de autorizados bool NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtEnvio.Nfe); //Verificar se o -procNfe.xml existe na past de autorizados bool procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe); //Se o XML de distribuição não estiver na pasta de autorizados if (!procNFeJaNaAutorizada) { if (!File.Exists(strArquivoNFeProc)) { Auxiliar.WriteLog("TaskNFeConsultaSituacao: Gerou o arquivo de distribuição através da consulta situação da NFe.", false); oGerarXML.XmlDistNFe(strArquivoNFe, strProtNfe, Propriedade.ExtRetorno.ProcNFe, versao); } } //Se o XML de distribuição não estiver ainda na pasta de autorizados if (!(procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe))) { //Move a nfeProc da pasta de NFE em processamento para a NFe Autorizada TFunctions.MoverArquivo(strArquivoNFeProc, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); //Atualizar a situação para que eu só mova o arquivo com final -NFe.xml para a pasta autorizado se //a procnfe já estiver lá, ou vai ficar na pasta emProcessamento para tentar gerar novamente. //Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe); } //Se a NFe não existir ainda na pasta de autorizados if (!(NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtEnvio.Nfe))) { //1-Mover a NFE da pasta de NFE em processamento para NFe Autorizada //2-Só vou mover o -nfe.xml para a pasta autorizados se já existir a -procnfe.xml, caso contrário vou manter na pasta EmProcessamento // para tentar gerar novamente o -procnfe.xml // Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 if (procNFeJaNaAutorizada) { TFunctions.MoverArquivo(strArquivoNFe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); } } else { //1-Se já estiver na pasta de autorizados, vou somente mover ela da pasta de XML´s em processamento //2-Só vou mover o -nfe.xml da pasta EmProcessamento se também existir a -procnfe.xml na pasta autorizados, caso contrário vou manter na pasta EmProcessamento // para tentar gerar novamente o -procnfe.xml // Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 if (procNFeJaNaAutorizada) { oAux.MoveArqErro(strArquivoNFe); } //oAux.DeletarArquivo(strArquivoNFe); } //Disparar a geração/impressão do UniDanfe. 03/02/2010 - Wandrey if (procNFeJaNaAutorizada) { try { string strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Autorizados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Path.GetFileName(strArquivoNFe); TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskNFeConsultaSituacao: (Falha na execução do UniDANFe) " + ex.Message, false); } } } if (File.Exists(strArquivoNFeProc)) { //Se já estiver na pasta de autorizados, vou somente excluir ela da pasta de XML´s em processamento Functions.DeletarArquivo(strArquivoNFeProc); } break; //danasa 11-4-2012 case "110": //Uso Denegado case "301": case "302": case "303": if (File.Exists(strArquivoNFe)) { /// /// se o ERP copiou o arquivo da NFe para a pasta em Processamento, o Uninfe irá montar o XML de distribuicao, caso nao exista, /// e imprimir o DANFE /// ProcessaNFeDenegada(emp, oLerXml, strArquivoNFe, protNFeElemento.OuterXml, versao); } //ProcessaNFeDenegada(emp, oLerXml, strArquivoNFe, retConsSitElemento.GetElementsByTagName("protNFe")[0].OuterXml, versao); break; default: //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoNFe); break; } //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveNFe); } } break; #endregion #region Nota fiscal cancelada case "101": //Cancelamento Homologado ou Nfe Cancelada goto case "100"; #endregion #region Nota fiscal Denegada case "110": //NFe Denegada goto case "100"; case "301": //NFe Denegada goto case "100"; case "302": //NFe Denegada goto case "100"; case "205": //Nfe já está denegada na base do SEFAZ goto case "100"; ///<<<<<<<<<< ??????????????????? >>>>>>>>>>>> /// //Ler o XML para pegar a data de emissão para criar a psta dos XML´s Denegados /* * if (File.Exists(strArquivoNFe)) * { * oLerXml.Nfe(strArquivoNFe); * * //Move a NFE da pasta de NFE em processamento para NFe Denegadas * if (!oAux.EstaDenegada(strArquivoNFe, oLerXml.oDadosNfe.dEmi)) * { * oAux.MoverArquivo(strArquivoNFe, PastaEnviados.Denegados, oLerXml.oDadosNfe.dEmi); * } * } * break;*/ #endregion #region Conteúdo para retirar a nota fiscal do fluxo case "TirarFluxo": //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoNFe); //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveNFe); break; #endregion default: break; } } }
public ExprTreeCompiler() { symbols = new List<Variable>(); functions = new Functions(); }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosPedSit = new DadosPedSit(); PedSit(emp, dadosPedSit);// NomeArquivoXML); if (vXmlNfeDadosMsgEhXML) { //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosPedSit.cUF, dadosPedSit.tpAmb, dadosPedSit.tpEmis, dadosPedSit.versao, dadosPedSit.mod); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oConsulta = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); object oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(dadosPedSit.cUF, Servico)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, NFe.Components.TpcnResources.cUF.ToString(), dadosPedSit.cUF.ToString()); wsProxy.SetProp(oCabecMsg, NFe.Components.TpcnResources.versaoDados.ToString(), dadosPedSit.versao); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oConsulta, wsProxy.NomeMetodoWS[0], oCabecMsg, this); //Efetuar a leitura do retorno da situação para ver se foi autorizada ou não //Na versão 1 não posso gerar o -procNfe, ou vou ter que tratar a estrutura do XML de acordo com a versão, a consulta na versão 1 é somente para obter o resultado mesmo. LerRetornoSitNFe(dadosPedSit.chNFe); //Gerar o retorno para o ERP oGerarXML.XmlRetorno(Propriedade.ExtEnvio.PedSit_XML, Propriedade.ExtRetorno.Sit_XML, this.vStrXmlRetorno); } else { string f = Path.GetFileNameWithoutExtension(NomeArquivoXML) + ".xml"; if (NomeArquivoXML.IndexOf(Empresas.Configuracoes[emp].PastaValidar, StringComparison.InvariantCultureIgnoreCase) >= 0) { f = Path.Combine(Empresas.Configuracoes[emp].PastaValidar, f); } oGerarXML.Consulta(TipoAplicativo.Nfe, f, dadosPedSit.tpAmb, dadosPedSit.tpEmis, dadosPedSit.chNFe, dadosPedSit.versao); } } catch (Exception ex) { string ExtRet = string.Empty; if (this.vXmlNfeDadosMsgEhXML) //Se for XML { ExtRet = Propriedade.ExtEnvio.PedSit_XML; } else //Se for TXT { ExtRet = Propriedade.ExtEnvio.PedSit_TXT; } try { TFunctions.GravarArqErroServico(NomeArquivoXML, ExtRet, Propriedade.ExtRetorno.Sit_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de pedido da consulta da situação da NFe, infelizmente //não posso fazser mais nada, o UniNFe vai tentar mantar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 22/03/2010 } } }
public static Quaternion GetSpotlightRotation(this Vehicle vehicle) => Functions.GetSpotlightRotation(vehicle);
protected override void Attack() { if (!Target.IsAttackTarget(this)) { Target = null; return; } bool ranged = CurrentLocation != Target.CurrentLocation && !Functions.InRange(CurrentLocation, Target.CurrentLocation, 3); Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation); ShockTime = 0; if (!ranged) { int damage = GetAttackPower(Stats[Stat.MinMC], Stats[Stat.MaxMC]); if (damage == 0) { return; } ActionTime = Envir.Time + 500; AttackTime = Envir.Time + AttackSpeed; Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation }); DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + 500, Target, damage, DefenceType.MACAgility); ActionList.Add(action); } else { if (Envir.Random.Next(5) > 0) { int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]); if (damage == 0) { return; } ActionTime = Envir.Time + 500; AttackTime = Envir.Time + AttackSpeed; Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, TargetID = Target.ObjectID, Type = 0 }); DelayedAction action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + 800, Target, damage, DefenceType.AC); ActionList.Add(action); } else { Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, TargetID = Target.ObjectID, Type = 1 }); TeleportTarget(4, 4); Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation); } } }
protected void Page_Load(object sender, EventArgs e) { string hostName = "den-vm-dg02"; // replace with your host. Rather than hardcode you would want to leverage a config file or similar approach int hostPort = 9000; string userName = "******"; string userPassword = ""; Boolean x = false; string fileName = "customers"; string invoiceID = ""; string salesrep = ""; int args = 0; string subroutine = ""; String AcctSelection = Request.QueryString["param"]; Pick D3 = new rocketsoftware.MVSP.Pick(); Functions func = new Functions(); x = D3.Connect(hostName, hostPort, userName, userPassword); bool acctstat = D3.Logto("acme", ""); // log over to the appropriate account String CustomerName = D3.FileReadv(fileName, AcctSelection, 1); // read the customer file to get the customer name lbl_CustomeName.Text = CustomerName; // assign the customer name to the custmer name display // Create DataTable DataTable dt = new DataTable(); //map results into a dataTable that can be then bound to the dataGrid // Create the Headers for the DataTable that needs to mapped so that the DataGrid can bind to it. dt.Columns.Add("Invoice#", typeof(string)); dt.Columns.Add("InvoiceDate", typeof(string)); dt.Columns.Add("OrderDate", typeof(string)); dt.Columns.Add("Terms", typeof(string)); dt.Columns.Add("Gross", typeof(Int32)); dt.Columns.Add("Discount", typeof(Int32)); dt.Columns.Add("NetInvoice", typeof(Int32)); // build the query to get the Invoice IDs that meet the selection criteria D3.ExecuteQuery("Query", "TRX.MST", "With cust.acct# = " + "" + AcctSelection + "" + " and with invoice.date", "by-dsnd invoice.date", " trx#", ""); int rowcount = D3.MVResultSetGetRowCount(); for (int i = 0; i < rowcount; i++) // loop through the ID list to read each matching Item { D3.MVResultSetNext(); invoiceID = D3.MVResultSetGetCurrentRow(); // gets the invoiceID from the result set to use for the subsequent readfile statements fileName = "TRX.MST"; string trxItem = D3.FileRead(fileName, invoiceID); string invoiceDate = func.Extract(trxItem, 21); args = 2; subroutine = "date_convert.sub"; Pick.mvSubroutine mysub = new Pick.mvSubroutine(subroutine, args, D3); mysub.SetArgs(0, invoiceDate); mysub.SetArgs(1, ""); mysub.MvCall(); // call date conversion invoiceDate = mysub.GetArgs(1); string orderDate = func.Extract(trxItem, 18); mysub.SetArgs(0, orderDate); mysub.MvCall(); // call date conversion orderDate = mysub.GetArgs(1); // convert to int to do math int TotalGross = Convert.ToInt32(func.Extract(trxItem, 31)); int TotalDiscount = Convert.ToInt32(func.Extract(trxItem, 32)); int TotalNet = (TotalGross - TotalDiscount); string Comments = func.Extract(trxItem, 23); string TerrID = func.Extract(trxItem, 8); fileName = "territories"; string Terr_Results = D3.FileRead(fileName, TerrID); if (D3.statusCode != 0) { salesrep = ""; }// no sales rep for the territory else { string territory = func.Extract(Terr_Results, 2); fileName = "salesreps"; salesrep = D3.FileReadv(fileName, territory, 1); } dt.Rows.Add(); dt.Rows[dt.Rows.Count - 1]["Invoice#"] = invoiceID; dt.Rows[dt.Rows.Count - 1]["InvoiceDate"] = invoiceDate; dt.Rows[dt.Rows.Count - 1]["OrderDate"] = orderDate; dt.Rows[dt.Rows.Count - 1]["Terms"] = "Net 30"; // no terms in database dt.Rows[dt.Rows.Count - 1]["Gross"] = TotalGross; dt.Rows[dt.Rows.Count - 1]["Discount"] = TotalDiscount; dt.Rows[dt.Rows.Count - 1]["NetInvoice"] = TotalNet; } Grid_Invoices.DataSource = dt; Grid_Invoices.DataBind(); D3.CloseConnection(); }
public IHttpActionResult GenerateCustomerOrder([FromBody] myCustomerOrder pOrder) { MovEncomenda myOrder; MovEncomendaLin myOrderLine; var byRefFalse = false; var stockAvailable = true; var affectsOtherLines = true; var fixedAssociation = true; var freeAssociation = true; var checkStock = false; var famForQty = false; var famForPrice = false; TpProcuraArtigo searchItem = 0; int numberLine; string itemCode; var errorDescription = ""; var result = new DocumentResult(); try { //pOrder = GetNewCustomerOrder(); myOrder = Eti.Aplicacao.Movimentos.MovEncomendasCli.GetNew(pOrder.DocTypeAbbrev, pOrder.SectionCode); myOrder.Cabecalho.CodExercicio = pOrder.FiscalYear; myOrder.Cabecalho.AplicacaoOrigem = "WS"; myOrder.Cabecalho.Data = pOrder.Date.Date; myOrder.Cabecalho.DataVencimento = pOrder.ExpirationDate; myOrder.Cabecalho.Hora = pOrder.Date.Hour.ToString("00") + ":" + pOrder.Date.Minute.ToString("00"); myOrder.Cabecalho.CodEntidade = pOrder.EntityCode; myOrder.AlteraEntidade((byte)TpEntidade.Cliente, myOrder.Cabecalho.CodEntidade, true); myOrder.Cabecalho.AbrevMoeda = pOrder.CurrencyCode; myOrder.AlteraMoeda(pOrder.CurrencyCode, ref byRefFalse, false); foreach (CustomerOrderLine line in pOrder.Lines.OrderBy(p => p.LineNumber)) { itemCode = line.ItemCode; numberLine = myOrder.Lines.Count + 1; myOrder.AddLin(ref numberLine); myOrderLine = myOrder.Lines[numberLine]; myOrderLine.TipoLinha = TpLinha.Artigo; myOrderLine.CodArtigo = itemCode; myOrder.AlteraArtigo(numberLine, ref itemCode, ref affectsOtherLines, ref fixedAssociation, ref freeAssociation, ref searchItem, checkStock, ref stockAvailable, ref famForQty, ref famForPrice); myOrderLine.DescArtigo = line.ItemDescription; myOrderLine.Quantidade = line.Quantity; myOrder.AlteraQuantidade(numberLine, myOrderLine.Quantidade, ref affectsOtherLines, false, ref stockAvailable); if (myOrder.TDocIvaIncluido) { line.UnitPriceExcludedVAT = line.UnitPriceExcludedVAT * (1 + line.VATTax / 100.0); } myOrderLine.PrecoUnitario = Convert.ToDouble(line.UnitPriceExcludedVAT); myOrder.AlteraPrecoUnitario(numberLine, myOrderLine.PrecoUnitario, ref byRefFalse); myOrderLine.TaxaIva = Convert.ToDouble(line.VATTax); myOrderLine.CodTaxaIva = Eti.Aplicacao.Tabelas.TaxasIvas.GetTaxaIva(Convert.ToDecimal(myOrderLine.TaxaIva)); myOrder.AlteraTaxaIVA(numberLine, myOrderLine.CodTaxaIva); myOrderLine.Desconto1 = line.Discount1; myOrder.AlteraDesconto(1, numberLine, myOrderLine.Desconto1); myOrderLine.Desconto2 = line.Discount2; myOrder.AlteraDesconto(2, numberLine, myOrderLine.Desconto2); myOrderLine.Desconto3 = line.Discount3; myOrder.AlteraDesconto(3, numberLine, myOrderLine.Desconto3); myOrderLine.DescontoValorLinha = line.DiscountValue; myOrder.AlteraDesconto(4, numberLine, myOrderLine.DescontoValorLinha); } var validate = myOrder.Validate(true); if (validate) { Eti.Aplicacao.Movimentos.MovEncomendasCli.Update(ref myOrder); } if (myOrder.EtiErrorDescription == "") { result = new DocumentResult() { ErrorDescription = myOrder.EtiErrorDescription, DocumentKey = new Helpers.DocumentKey() { SectionCode = myOrder.Cabecalho.CodSeccao, DocTypeAbbrev = myOrder.Cabecalho.AbrevTpDoc, FiscalYear = myOrder.Cabecalho.CodExercicio, Number = myOrder.Cabecalho.Numero } }; if (pOrder.GetReportBytes) { result.reportBytes = Functions.GetReportBytes(TpDocumentoAEmitir.Encomendas, result.DocumentKey); } } else { result.ErrorDescription = myOrder.EtiErrorDescription; } } catch (Exception ex) { errorDescription = string.Format("{0}.{1}.{2}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name, ex.Message); result.ErrorDescription = errorDescription; } return(Ok(result)); }
public Client InsertClient(Client ins) { //...Get User and Date Data... string strTrx = "Insert_Client"; //...Database Connection... DataBaseConnection dbConn = new DataBaseConnection(); SqlConnection con = dbConn.SqlConn(); con.Open(); //...Command Interface... SqlCommand cmdI = con.CreateCommand(); SqlTransaction trx; trx = con.BeginTransaction(strTrx); cmdI.Connection = con; cmdI.Transaction = trx; try { //...Insert Record... cmdI.Parameters.Clear(); cmdI.CommandText = "f_Admin_Insert_Client"; cmdI.CommandType = System.Data.CommandType.StoredProcedure; cmdI.Parameters.AddWithValue("@Name", ins.Name); // varchar(50) cmdI.Parameters.AddWithValue("@APIKey", ""); //...Return new ID... ins.ClientId = (int)cmdI.ExecuteScalar(); //...Commit Transaction... trx.Commit(); cmdI.Connection.Close(); } catch (SqlException ex) { if (trx != null) trx.Rollback(); //...Save Error to Log... Functions func = new Functions(); func.LogError(ex.ToString()); } finally { //...Check for close and respond accordingly.. if (con.State != ConnectionState.Closed) { con.Close(); } //...Clean up... con.Dispose(); cmdI.Dispose(); trx.Dispose(); } return ins; }
public void AttemptAction(ObjectAction action) { if (CEnvir.Now < NextActionTime || ActionQueue.Count > 0) { return; } if (CEnvir.Now < ServerTime) { return; //Next Server response Time. } switch (action.Action) { case MirAction.Moving: if (CEnvir.Now < MoveTime) { return; } break; case MirAction.Attack: action.Extra[2] = Functions.GetElement(Stats); if (GameScene.Game.Equipment[(int)EquipmentSlot.Amulet]?.Info.ItemType == ItemType.DarkStone) { foreach (KeyValuePair <Stat, int> stats in GameScene.Game.Equipment[(int)EquipmentSlot.Amulet].Info.Stats.Values) { switch (stats.Key) { case Stat.FireAffinity: action.Extra[2] = Element.Fire; break; case Stat.IceAffinity: action.Extra[2] = Element.Ice; break; case Stat.LightningAffinity: action.Extra[2] = Element.Lightning; break; case Stat.WindAffinity: action.Extra[2] = Element.Wind; break; case Stat.HolyAffinity: action.Extra[2] = Element.Holy; break; case Stat.DarkAffinity: action.Extra[2] = Element.Dark; break; case Stat.PhantomAffinity: action.Extra[2] = Element.Phantom; break; } } } MagicType attackMagic = MagicType.None; if (AttackMagic != MagicType.None) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != AttackMagic) { continue; } if (CEnvir.Now < pair.Value.NextCast) { break; } if (AttackMagic == MagicType.Karma) { if (Stats[Stat.Health] * pair.Value.Cost / 100 > CurrentHP || Buffs.All(x => x.Type != BuffType.Cloak)) { break; } } else if (pair.Value.Cost > CurrentMP) { break; } attackMagic = AttackMagic; break; } } if (CanPowerAttack && TargetObject != null) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != MagicType.Slaying) { continue; } if (pair.Value.Cost > CurrentMP) { break; } attackMagic = pair.Key.Magic; break; } } if (CanThrusting && GameScene.Game.MapControl.CanEnergyBlast(action.Direction)) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != MagicType.Thrusting) { continue; } if (pair.Value.Cost > CurrentMP) { break; } attackMagic = pair.Key.Magic; break; } } if (CanHalfMoon && (TargetObject != null || (GameScene.Game.MapControl.CanHalfMoon(action.Direction) && (GameScene.Game.MapControl.HasTarget(Functions.Move(CurrentLocation, action.Direction)) || attackMagic != MagicType.Thrusting)))) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != MagicType.HalfMoon) { continue; } if (pair.Value.Cost > CurrentMP) { break; } attackMagic = pair.Key.Magic; break; } } if (CanDestructiveBlow && (TargetObject != null || (GameScene.Game.MapControl.CanDestructiveBlow(action.Direction) && (GameScene.Game.MapControl.HasTarget(Functions.Move(CurrentLocation, action.Direction)) || attackMagic != MagicType.Thrusting)))) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != MagicType.DestructiveSurge) { continue; } if (pair.Value.Cost > CurrentMP) { break; } attackMagic = pair.Key.Magic; break; } } if (attackMagic == MagicType.None && CanFlameSplash && (TargetObject != null || GameScene.Game.MapControl.CanDestructiveBlow(action.Direction))) { foreach (KeyValuePair <MagicInfo, ClientUserMagic> pair in Magics) { if (pair.Key.Magic != MagicType.FlameSplash) { continue; } if (pair.Value.Cost > CurrentMP) { break; } attackMagic = pair.Key.Magic; break; } } if (CanBladeStorm) { attackMagic = MagicType.BladeStorm; } else if (CanDragonRise) { attackMagic = MagicType.DragonRise; } else if (CanFlamingSword) { attackMagic = MagicType.FlamingSword; } action.Extra[1] = attackMagic; break; case MirAction.Mount: return; } SetAction(action); int attackDelay; switch (action.Action) { case MirAction.Standing: NextActionTime = CEnvir.Now + Globals.TurnTime; CEnvir.Enqueue(new C.Turn { Direction = action.Direction }); if ((GameScene.Game.MapControl.MapButtons & MouseButtons.Right) != MouseButtons.Right) { GameScene.Game.CanRun = false; } break; case MirAction.Harvest: NextActionTime = CEnvir.Now + Globals.HarvestTime; CEnvir.Enqueue(new C.Harvest { Direction = action.Direction }); GameScene.Game.CanRun = false; break; case MirAction.Moving: MoveTime = CEnvir.Now + Globals.MoveTime; CEnvir.Enqueue(new C.Move { Direction = action.Direction, Distance = MoveDistance }); GameScene.Game.CanRun = true; break; case MirAction.Attack: attackDelay = Globals.AttackDelay - Stats[Stat.AttackSpeed] * Globals.ASpeedRate; attackDelay = Math.Max(800, attackDelay); AttackTime = CEnvir.Now + TimeSpan.FromMilliseconds(attackDelay); if (BagWeight > Stats[Stat.BagWeight]) { AttackTime += TimeSpan.FromMilliseconds(attackDelay); } CEnvir.Enqueue(new C.Attack { Direction = action.Direction, Action = action.Action, AttackMagic = MagicType }); GameScene.Game.CanRun = false; break; case MirAction.Spell: NextMagicTime = CEnvir.Now + Globals.MagicDelay; if (BagWeight > Stats[Stat.BagWeight]) { NextMagicTime += Globals.MagicDelay; } CEnvir.Enqueue(new C.Magic { Direction = action.Direction, Action = action.Action, Type = MagicType, Target = AttackTargets?.Count > 0 ? AttackTargets[0].ObjectID : 0, Location = MagicLocations?.Count > 0 ? MagicLocations[0] : Point.Empty }); GameScene.Game.CanRun = false; break; case MirAction.Mining: attackDelay = Globals.AttackDelay - Stats[Stat.AttackSpeed] * Globals.ASpeedRate; attackDelay = Math.Max(800, attackDelay); AttackTime = CEnvir.Now + TimeSpan.FromMilliseconds(attackDelay); if (BagWeight > Stats[Stat.BagWeight]) { AttackTime += TimeSpan.FromMilliseconds(attackDelay); } CEnvir.Enqueue(new C.Mining { Direction = action.Direction }); GameScene.Game.CanRun = false; break; default: GameScene.Game.CanRun = false; break; } ServerTime = CEnvir.Now.AddSeconds(5); }
private IAsyncResult BeginMethod(Functions funcName, JObject request, MethodCheckRequestParameters check, AsyncCallback callBackMethod) { var methodDelegate = new KORTClientMethodDelegate(Method); return methodDelegate.BeginInvoke(funcName, request, check, callBackMethod, methodDelegate); }
public override bool SpawnMinion(MonsterObject mob) { return(mob.Spawn(CurrentMap, Functions.Move(CurrentLocation, Functions.ShiftDirection(Direction, 3)))); }
public bool RemovePicture(int PictureId) { bool Removed = true; //...Check Id... if (PictureId != 0) { //...Get Picture... //Picture pic = GetPicture(PictureId); //string path = pic.PicUrl.Substring(pic.PicUrl.IndexOf("/Images")); //path = path.Replace('/','\\'); //path = Path.Combine(Server.MapPath("~"), //System.IO.File.Delete(pic.PicUrl); //...Get User and Date Data... string strTrx = "Remove_Picture"; //...Database Connection... DataBaseConnection dbConn = new DataBaseConnection(); SqlConnection con = dbConn.SqlConn(); con.Open(); //...Command Interface... SqlCommand cmdI = con.CreateCommand(); SqlTransaction trx; trx = con.BeginTransaction(strTrx); cmdI.Connection = con; cmdI.Transaction = trx; try { //...Insert Record... cmdI.Parameters.Clear(); cmdI.CommandText = "f_Admin_Remove_Picture"; //cmdI.Connection.Open(); cmdI.CommandType = System.Data.CommandType.StoredProcedure; cmdI.Parameters.AddWithValue("@PictureId", PictureId); // int //...Return new ID... int ret = (int)cmdI.ExecuteScalar(); //...Commit Transaction... trx.Commit(); cmdI.Connection.Close(); } catch (SqlException ex) { if (trx != null) { trx.Rollback(); Removed = false; } //...Save Error to Log... Functions func = new Functions(); func.LogError(ex.ToString()); } finally { //...Check for close and respond accordingly.. if (con.State != ConnectionState.Closed) { con.Close(); } //...Clean up... con.Dispose(); cmdI.Dispose(); trx.Dispose(); } } return Removed; }
protected override void ProcessTarget() { if (Target == null || !CanAttack || Target.PercentHealth == 100) { return; } if (PercentHealth != 100 && Envir.Time < FearTime) { HealMyself(); return; } if (InAttackRange() && Envir.Time < FearTime && Target.Race != ObjectType.Player) { HealTarget(); return; } FearTime = Envir.Time + 5000; if (Envir.Time < ShockTime) { Target = null; return; } if (Target.Race == ObjectType.Player) { int dist = Functions.MaxDistance(CurrentLocation, Target.CurrentLocation); if (dist < 3) { MirDirection dir = Functions.DirectionFromPoint(Target.CurrentLocation, CurrentLocation); if (Walk(dir)) { return; } switch (Envir.Random.Next(2)) //No favour { case 0: for (int i = 0; i < 4; i++) { dir = Functions.NextDir(dir); if (Walk(dir)) { return; } } break; default: for (int i = 0; i < 4; i++) { dir = Functions.PreviousDir(dir); if (Walk(dir)) { return; } } break; } } SearchTarget(); } }
internal string?GetValue(string localName) { if (_enumerable == null) { return(null); } if (_enumerator == null) { _enumerator = _enumerable.GetEnumerator(); } int origIdx = _index; int idx = origIdx; if (!_enumerator.MoveNext()) { idx = -1; _enumerator = _enumerable.GetEnumerator(); if (!_enumerator.MoveNext()) { _enumerable = null; return(null); } } idx++; while (idx != origIdx) { string?curName = Functions.GetLocalName(_enumerator.Current); if (localName == curName) { _index = idx; return(Functions.GetValue(_enumerator.Current)); } if (!_enumerator.MoveNext()) { idx = -1; if (origIdx < 0) { _enumerator = null; return(null); } _enumerator = _enumerable.GetEnumerator(); if (!_enumerator.MoveNext()) { Debug.Fail("Original enumerator had elements, new one does not"); _enumerable = null; return(null); } } idx++; } return(null); }
public void AddFunction(FunctionInfo fi) { Functions.Add(fi); }
private void OnFunctionChanged(object sender, EventArgs e) { m_function = (Functions)m_functionComboBox.SelectedIndex; switch (m_function) { case Functions.Forward: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = m_altitudeTextBox.ReadOnly = false; m_XTextBox.ReadOnly = m_YTextBox.ReadOnly = m_ZTextBox.ReadOnly = true; break; case Functions.Inverse: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = m_altitudeTextBox.ReadOnly = true; m_XTextBox.ReadOnly = m_YTextBox.ReadOnly = m_ZTextBox.ReadOnly = false; break; } }
private void generateButton_Click(object sender, EventArgs e) { model = null; alpha = null; resultRichTextBox.Text = ""; double m, d, delta; int n; try { m = Convert.ToDouble(mTextBox.Text); d = Convert.ToDouble(dTextBox.Text); n = Convert.ToInt32(nTextBox.Text); delta = Convert.ToDouble(duTextBox.Text); } catch (FormatException) { MessageBox.Show("Введены некорректные данные.", "Ошибка ввода"); return; } if (l1RadioButton.Checked) { functions = new ObjectFunction[1]; functions[0] = (u => { return(u); }); alpha = new double[1] { 0 }; objectFunction = Function.LinearFunction1; funcType = Functions.Linear_1; } else if (l2RadioButton.Checked) { functions = new ObjectFunction[2]; functions[0] = (u => { return(1); }); functions[1] = (u => { return(u); }); alpha = new double[2] { 0, 0 }; objectFunction = Function.LinearFunction2; funcType = Functions.Linear_2; } else if (nl1RadioButton.Checked) { functions = new ObjectFunction[3]; functions[0] = (u => { return(1); }); functions[1] = (u => { return(u); }); functions[2] = (u => { return(u * u); }); gradient = new ObjectFunction[3]; gradient[0] = (u => { return(1); }); gradient[1] = (u => { return(u); }); gradient[2] = (u => { return(u * u); }); alpha = new double[3] { 0, 0, 0 }; objectFunction = Function.NonLinearFunction1; funcType = Functions.NonLinear_1; } else if (nl2RadioButton.Checked) { functions = new ObjectFunction[2]; /*functions[0] = (u => { return Math.Sin(u); }); * functions[1] = (u => { return Math.Cos(u); });*/ gradient = new ObjectFunction[2]; /*gradient[0] = (u => { return Math.Sin(u); }); * gradient[1] = (u => { return Math.Cos(u); });*/ gradient[0] = (u => { return(Math.Pow(u, alpha[1])); }); gradient[1] = (u => { return(alpha[0] * Math.Pow(u, alpha[1]) * Math.Log(u)); }); alpha = new double[2] { 0, 0 }; objectFunction = Function.NonLinearFunction2; funcType = Functions.NonLinear_2; } else { MessageBox.Show("Выберите объект"); return; } adaptButton.Enabled = true; showButton.Enabled = true; originalObject = new Dictionary <double, double>(); for (double i = 0.01; i < delta * n; i += delta) { originalObject.Add(i, objectFunction(i) + Statistics.MpcGenerator(m, 0, d, 1)[0]); } }