public Basico(int id, DateTime cadastro, DateTime atualizacao, Boolean ativo) { this._id = id; this._cadastro = cadastro; this._atualizacao = atualizacao; this._ativo = ativo; }
private Boolean runTest( Boolean verbose ) { int iCountErrors = 0; int iCountTestcases = 0; try { ++iCountTestcases; if ( verbose ) Console.WriteLine( "Make sure GetRemainingCount is correctly incremented decremented for different arglists" ); try { NormClass.argit1( __arglist( ) ); NormClass.argit1( __arglist( "a", "b", "c", "a", "b", "c", "a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c","a", "b", "c" ) ); NormClass.argit1( __arglist( ) ); NormClass.argit1( __arglist(typeof(System.String), null, (int) 1975, (long) 6, (float) 4.3, BindingFlags.NonPublic, new Object(), new Hashtable(), (char) 'a', (byte) 0x80, "Some String", Guid.NewGuid(), Int16.MinValue, DateTime.Now)); NormClass.argit1( __arglist( ) ); } catch (Exception ex) { ++iCountErrors; Console.WriteLine( "Err_001a, Unexpected exception was thrown ex: " + ex.ToString() ); } } catch (Exception exc_runTest) { ++iCountErrors; Console.Error.WriteLine (strName+" "+strTest+" "+strPath); Console.Error.WriteLine ("Unexpected Exception (runTest99): "+exc_runTest.ToString()); } Console.WriteLine (); Console.WriteLine ("FINAL TEST RESULT:" + strName+" "+strTest+" "+strPath); Console.WriteLine (); if ( iCountErrors == 0 ) { return true; } else { return false;} }
private static Boolean KawigiEdit_RunTest(int testNum, int p0, int p1, Boolean hasAnswer, long p2) { Console.Write("Test " + testNum + ": [" + p0 + "," + p1); Console.WriteLine("]"); Apportionment obj; long answer; obj = new Apportionment(); DateTime startTime = DateTime.Now; answer = obj.numberOfSquares(p0, p1); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p2); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = answer == p2; } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; }
public Basico(DataRow row) { this._id = Convert.ToInt32(row["id"]); this._cadastro = Convert.ToDateTime(row["cadastro"]); this._atualizacao = Convert.ToDateTime(row["atualizacao"]); this._ativo = Convert.ToBoolean(row["ativo"]); }
//获取投票数量的比例 public string GetItemproportion(string pis_xxid, Boolean bl) { string rValue; HyoaClass.DAO db = new HyoaClass.DAO(); //总参与投票数 double ls_tpall; string ls_sql1 = " Select * from hyk_whzx_tpgl_tpmx where hy_tpztid ='" + this.txtdocid.Value + "' "; DataTable dt1 = db.GetDataTable(ls_sql1); ls_tpall = dt1.Rows.Count; //得到某一个选项投票数 double ls_tpxx; string ls_sql2 = " Select * from hyk_whzx_tpgl_tpmx where hy_tpztid ='" + this.txtdocid.Value + "' and hy_tpxxid ='" + pis_xxid + "' "; DataTable dt2 = db.GetDataTable(ls_sql2); ls_tpxx = dt2.Rows.Count; double ls_num = 0.0; if (ls_tpxx != 0) { ls_num = (ls_tpxx / ls_tpall) * 100; } if (bl) { rValue = ls_num.ToString("#0.#0") + "%"; } else { rValue = ls_num.ToString("#0.#0"); } dt1.Clear(); dt2.Clear(); db.Close(); return rValue; }
public string GetServicesList(string providerName, Boolean ViewAsXml) { SimpleFacade wSimpleFacade = CreateSimpleFacade(); return wSimpleFacade.GetServicesList(providerName, ViewAsXml); }
private static Boolean KawigiEdit_RunTest(int testNum, string p0, Boolean hasAnswer, int p1) { Console.Write("Test " + testNum + ": [" + "\"" + p0 + "\""); Console.WriteLine("]"); RaiseThisBarn obj; int answer; obj = new RaiseThisBarn(); DateTime startTime = DateTime.Now; answer = obj.calc(p0); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p1); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = answer == p1; } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; }
public void checkCtaAvailability(int type, int minimumAward, Boolean isDirect, Action<Boolean, Boolean> action) { developerCtaInterface.Call("checkCtaAvailability", type, minimumAward, isDirect); if (actionPool.ContainsKey (minimumAward * MAX_TYPE_COUNT + type)) actionPool.Remove (minimumAward * MAX_TYPE_COUNT + type); actionPool.Add (minimumAward * MAX_TYPE_COUNT + type, action); }
public override void setAttackSettings(string attack, float xPos, float yPos) { //Should set damage and projectileSpeed variables based on the key //This method is called when calling spawnProjectile. if (xPos < 0) { startedRight = true; } else { startedRight = false; } //setup attributes of each attack if (attack == "blackOrbAttack") { damage = 1; projectileSpeed = blackOrbSpeed; angularVelocity = 0; } else if (attack == "unblockableAttack") { damage = 3; projectileSpeed = unblockableOrbSpeed; angularVelocity = 0; } }
public Boolean TestToBoolean(Boolean testSubject){ strLoc = "Loc_498yv"; Boolean b1 = false; Boolean b2 = false; Boolean pass = false; Boolean excthrown = false; Object exc1 = null; Object exc2 = null; try { b1 = ((IConvertible)testSubject).ToBoolean(null); pass = true; excthrown = false; } catch (Exception exc) { exc1 = exc; pass = false; excthrown = true; } try { b2 = Convert.ToBoolean(testSubject); pass = pass & true; } catch (Exception exc) { exc2 = exc; pass = false; excthrown = excthrown & true; } if(excthrown) if(exc1.GetType() == exc2.GetType()) return true; else return false; else if(pass && b1 == b2) return true; else return false; }
double updateRate = 4.0; // 4 updates per sec. // Use this for initialization void Start () { toggleDisplay = false; transformList = new string[] {"Hips", "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase", "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase", "Spine", "Spine1", "Spine2", "Spine3", "Neck", "Neck1", "Head", "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand", "RightShoulder", "RightArm", "RightForeArm", "RightHand", "root" }; foreach (string s in transformList) { GameObject o = GameObject.Find (s); if (o == null) { Debug.Log ("Could not find object: " + s); } else { objects.Add (s, o); rotationOffsets.Add ( s, Quaternion.identity ); initialOrientation.Add ( s, o.transform.localRotation ); } } data = new Byte[8192]; Connect(); }
protected void Page_Load(object sender, EventArgs e) { try { isSysSettingNameLoad = false; this.cmbSysSettingName.Load += new EventHandler(cmbSysSettingName_Load); type = Request["Type"]; iSysSetting = ServiceAgent.getInstance().GetMaintainObjectByName<ISysSetting>(WebConstant.MaintainSysSettingObject); pmtMessage1 = this.GetLocalResourceObject(Pre + "_pmtMessage1").ToString(); pmtMessage2 = this.GetLocalResourceObject(Pre + "_pmtMessage2").ToString(); pmtMessage3 = this.GetLocalResourceObject(Pre + "_pmtMessage3").ToString(); pmtMessage4 = this.GetLocalResourceObject(Pre + "_pmtMessage4").ToString(); pmtMessage5 = this.GetLocalResourceObject(Pre + "_pmtMessage5").ToString(); pmtMessage6 = this.GetLocalResourceObject(Pre + "_pmtMessage6").ToString(); if (!this.IsPostBack) { userName = Master.userInfo.UserId; this.HiddenUserName.Value = userName; initLabel(); //bindTable(null, DEFAULT_ROWS); initcmbSysSettingNameList(); } ScriptManager.RegisterStartupScript(this.updatePanelAll, typeof(System.Object), "InitControl", "initControls();", true); } catch (FisException ex) { showErrorMessage(ex.mErrmsg); } catch (Exception ex) { showErrorMessage(ex.Message); } }
public Document( Int16 _TypeId, Int64 _Serial, Int32 _SignedUser, DateTime _Date, Boolean _Printed, String _DocumentShortName, String _DocumentFullName, String _MedexDataTable, String _DocumentBody, String _DocumentHeader, Boolean _SetDeleted ) { TypeId = _TypeId; Serial = _Serial; SignedUser = _SignedUser; Date = _Date; Printed = _Printed; DocumentShortName = _DocumentShortName; DocumentFullName = _DocumentFullName; MedexDataTable = _MedexDataTable; DocumentBody = _DocumentBody; DocumentHeader = _DocumentHeader; SetDeleted = _SetDeleted; }
public void PropagateSettingToApplyMethodCollection(Boolean applyOptional) { var attribute = new ApplyByRegistrationAttribute(typeof(FakeMapping)) { ApplyOptional = applyOptional }; var applyMethods = attribute.GetApplyMethods(typeof(FakeAggregate)); Assert.Equal(applyOptional, applyMethods.ApplyOptional); }
// Update is called once per frame void Update() { int seconds = DateTime.Now.Second % (int)DAYNIGHT_CYCLE_FREQ; if (seconds == 0) { if (_dayNightSeconds != seconds) { if (_day) { _currentTopColor -= _dayNightDiffTop; _currentBottomColor -= _dayNightDiffBottom; } else { _currentTopColor += _dayNightDiffTop; _currentBottomColor += _dayNightDiffBottom; } UpdateGradient(_currentTopColor, _currentBottomColor); _dayNightSeconds = seconds; if (_currentTopColor.b < _nightTopColor.b) _day = false; if (_currentTopColor.b > _dayTopColor.b) _day = true; } } else _dayNightSeconds = -1; }
public ForumCollection<Forum> GetForums(Boolean active) { ForumCollection<Forum> _coll = new ForumCollection<Forum>(this.ConnectionString); ArgumentsList _arg = new ArgumentsList(new ArgumentsListItem("Active", active.ToString())); _coll.LitePopulate(_arg, false, null); return _coll; }
/// <summary> /// Loads all the Customers and its Addresses on the gridview /// </summary> protected void loadCustomers(int idRoute) { Customers customers = new Customers(); DataTable dt; dt = customers.getCustomersAndAddressesToEdit(idRoute); if (dt != null && dt.Rows.Count > 0) { showCustomers = true; GridView1.DataSource = dt; GridView1.DataBind(); } else { showCustomers = false; } DataTable addressesByRoute; addressesByRoute = customers.getCustomersAndAddressesByRoute(idRoute); for (int i = 0; i < addressesByRoute.Rows.Count; i++) { this.idAddressesByRoute.Add(addressesByRoute.Rows[i].ItemArray[0].ToString()); } this.setDataToScript(this.idAddressesByRoute); }
// Update is called once per frame void Update() { if (moving) { transform.position = Vector3.MoveTowards (transform.position, cameraPosition, 10f * Time.deltaTime); Vector3 newScale = transform.localScale; newScale.x = newScale.x + 12f * Time.deltaTime; newScale.y = newScale.y + 12f * Time.deltaTime; newScale.z = newScale.z + 12f * Time.deltaTime; transform.localScale = newScale; } if (animationLock && !selectedWorld && !animationReallyStarted && !startedAnimation && Math.Abs (transform.position.z - cameraPosition.z) < 0.01f) { moving = false; anim.Play ("open"); startedAnimation = true; } if (!selectedWorld && startedAnimation && anim.GetCurrentAnimatorStateInfo (0).IsName ("open")) { startedAnimation = false; animationReallyStarted = true; } if (!selectedWorld && animationReallyStarted && !anim.GetCurrentAnimatorStateInfo (0).IsName ("open")) { animationReallyStarted = false; selectedWorld = true; worldSelectScript.SelectedWorld (worldNumber); } }
private static Boolean KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, Boolean hasAnswer, int p3) { Console.Write("Test " + testNum + ": [" + p0 + "," + p1 + "," + p2); Console.WriteLine("]"); ExcitingGame obj; int answer; obj = new ExcitingGame(); DateTime startTime = DateTime.Now; answer = obj.howMany(p0, p1, p2); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p3); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = answer == p3; } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; }
void OnCollisionExit2D(Collision2D other) { if (other.gameObject.tag == "Ground") { isGrounded = false; } }
protected void grdContainers_Sorting(object sender, GridViewSortEventArgs e) { try { if (sortingColumn != null && sortingColumn.Equals(e.SortExpression)) // if the list is already sorted by this column, { // toggle ascending/descending sortAscending = !sortAscending; } else // else, set new column and set sorting to ascending { sortingColumn = e.SortExpression; sortAscending = true; // set false because default is ascending } ViewState["sortingColumn"] = sortingColumn; ViewState["sortAscending"] = sortAscending; updateGridView(); } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { LogError.logError(ex); Response.Redirect("../errorpages/error.aspx"); } }
public void Read(BinaryReader r) { //if (r == null) throw new ArgumentNullException("r"); FResult = new StringBuilder(r.ReadString()); FSeparator = r.ReadString(); FEmpty = r.ReadBoolean(); }
public Service() { //log4net.Util.LogLog.InternalDebugging = true; ODws = new CustomService(this.Context);//INFO we can extend this for other service types try { useODForValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]); } catch (Exception e) { String error = "Missing or invalid value for UseODForValues. Must be true or false"; log.Fatal(error); throw new SoapException("Invalid Server Configuration. " + error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } try { requireAuthToken = Boolean.Parse(ConfigurationManager.AppSettings["requireAuthToken"]); } catch (Exception e) { String error = "Missing or invalid value for requireAuthToken. Must be true or false"; log.Fatal(error); throw new SoapException(error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } }
private static Boolean KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, Boolean hasAnswer, double p3) { Console.Write("Test " + testNum + ": [" + p0 + "," + p1 + "," + p2); Console.WriteLine("]"); TwoLotteryGames obj; double answer; obj = new TwoLotteryGames(); DateTime startTime = DateTime.Now; answer = obj.getHigherChanceGame(p0, p1, p2); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p3); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = Math.Abs(p3 - answer) <= 1e-9 * Math.Max(1.0, Math.Abs(p3)); } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; }
public static string chk_image(string file, string path, string url, Boolean cache) { if (cache) { if (File.Exists(path + file)) { return path + file; } else if (is_online) { WebClient dl = new WebClient(); dl.DownloadFile(url, path + file); return path + file; } else { return "offline_icon.png"; } } else { if (File.Exists(path + file)) { return path + file; } else if (is_online) { return url; } else { return "offline_icon.png"; } } }
public FMotionStreakElement(Vector2 position, FMotionStreakElement previousElement) : base() { centerVertice=position; previous=previousElement; if (previousElement!=null) { Vector2 diff=centerVertice-previousElement.centerVertice; float dist = (float)Math.Sqrt(Vector2.SqrMagnitude(diff)); if (dist>0.01f) { Vector2 normalizedDiff=diff.normalized; direction=new Vector2(-normalizedDiff.y,normalizedDiff.x); valid=true; ChangeWidth(1.0f); } else { if (previousElement.valid) { direction=previousElement.direction; valid=true; ChangeWidth(1.0f); } else { valid=false; width=0; } } } else { valid=false; width=0; } }
/// <summary> /// deserialize from the reader to recreate the struct /// </summary> /// <param name="r">BinaryReader</param> void IBinarySerialize.Read(System.IO.BinaryReader r) { _delimiter = r.ReadString(); _accumulator = new StringBuilder(r.ReadString()); if (_accumulator.Length != 0) this.IsNull = false; }
//Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd) { _archive = archive; _originallyInArchive = true; _diskNumberStart = cd.DiskNumberStart; _versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract; _generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag; CompressionMethod = (CompressionMethodValues)cd.CompressionMethod; _lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified)); _compressedSize = cd.CompressedSize; _uncompressedSize = cd.UncompressedSize; _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader; /* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength * but entryname/extra length could be different in LH */ _storedOffsetOfCompressedData = null; _crc32 = cd.Crc32; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = DecodeEntryName(cd.Filename); _lhUnknownExtraFields = null; //the cd should have these as null if we aren't in Update mode _cdUnknownExtraFields = cd.ExtraFields; _fileComment = cd.FileComment; _compressionLevel = null; }
public USUARIO addUser(String nombre, String clave, int institucionid, int perfil, Boolean validate) { USUARIO user = new USUARIO(); List<USUARIO> users = new List<USUARIO>(); if (validate) { users = obtainUserByUserName(nombre); } if (users.Count <= 0) { try { user.USUARIOID = 0; user.NOMBRE = nombre; user.CLAVE = InstitucionesUtil.Encripta(clave); user.INSTITUCIONID = institucionid; user.PERFIL = perfil; Datos.USUARIOs.Add(user); Datos.SaveChanges(); } catch (Exception ex) { string x = ex.Message; } } return user; }
void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.tag == "Ground") { isGrounded = true; } }
internal HotPlugin(IPlugin plugin) { _plugin = plugin; _isLoaded = false; _isEnabled = false; }
internal void InitWindow() { windowID = UnityEngine.Random.Range(1000, 2000000) + KerbalAlarmClock._AssemblyName.GetHashCode(); windowRect = new Rect(0, 0, 400, 200); Visible = false; }
protected void btnSignUp_Click(object sender, EventArgs e) { string userType = "h"; lbsuccess.Text = ""; System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(); sc.ConnectionString = @"Data Source=aay09edjn65sf6.cpcbbo8ggvx6.us-east-1.rds.amazonaws.com;Initial Catalog=RoomMagnet;Persist Security Info=True;User ID=fahrenheit;Password=cis484fall"; sc.Open(); String firstName = HttpUtility.HtmlEncode(tbFirstName.Text); String lastName = HttpUtility.HtmlEncode(tbLastName.Text); String email = HttpUtility.HtmlEncode(tbTenantEmail.Text); String birthday = HttpUtility.HtmlEncode(tbBirthday.Text); // WILL NEED A METHOD TO CONFIRM EMAIL - DO THAT NEXT String password = HttpUtility.HtmlEncode(tbPassword.Text); String passConfirm = HttpUtility.HtmlEncode(tbPassConfirm.Text); Boolean passwordCorrect = passwordConfirm(password, passConfirm); string address = HttpUtility.HtmlEncode(tbAddress.Text); //splitting up address string[] testArray = new string[2]; int count = 2; string[] seperator = { " " }; string[] strList = address.Split(seperator, count, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < 2; i++) { testArray[i] = strList[i]; } string HouseNumber = testArray[0]; string street = testArray[1]; string DOB = tbBirthday.Text; string city = HttpUtility.HtmlEncode(tbCity.Text); string state = ddState.SelectedValue; string zip = HttpUtility.HtmlEncode(tbZip.Text); DateTime now = DateTime.Now; string phoneNumber = HttpUtility.HtmlEncode(tbPhoneNumber.Text); Tenant tempTenant = new Tenant(firstName, lastName, email, HouseNumber, street, city, state, zip, DOB, userType); // Password security validation Boolean capital = false; Boolean number = false; Boolean special = false; Boolean whiteSpace = true; Boolean minLength = false; Boolean passwordValid = false; if (password.Any(char.IsUpper)) { capital = true; if (password.Any(char.IsDigit)) { number = true; for (int i = 0; i < password.Length; i++) { if (password[i] == '!' || password[i] == '?' || password[i] == '`' || password[i] == '~' || password[i] == '@' || password[i] == '#' || password[i] == '$' || password[i] == '%' || password[i] == '^' || password[i] == '&' || password[i] == '*' || password[i] == '(' || password[i] == ')' || password[i] == '-' || password[i] == '_' || password[i] == '+' || password[i] == '=' || password[i] == ',' || password[i] == '<' || password[i] == '.' || password[i] == '>' || password[i] == '/' || password[i] == '?' || password[i] == '[' || password[i] == '{' || password[i] == ']' || password[i] == '}' || password[i] == ';' || password[i] == ':' || password[i] == '"' || password[i] == '|') { special = true; if (password.Any(char.IsPunctuation)) { special = true; if (password.Length >= 8) { minLength = true; if (password.Any(char.IsWhiteSpace)) { whiteSpace = false; } } } } } } } if (capital == true && number == true && special == true && minLength == true && whiteSpace == true) { passwordValid = true; lblDebug.Text = ""; } else { if (minLength == false) { lblDebug.Text = "Your password must have at least 8 characters"; } if (whiteSpace == false) { lblDebug.Text = "Your password cannot have space"; } if (capital == false || number == false || special == false) { lblDebug.Text = "Your password does not inclueded number, capital letter or special character!"; } } // Email Validation Boolean atSign = false; Boolean comma = false; Boolean emailValid = false; for (int i = 0; i < email.Length; i++) { if (email[i] == '@') { atSign = true; } else if (email[i] == '.') { comma = true; } else { lblDebug.Text = "Please enter correct email format"; } } if (tbTenantEmail.Text == "") { lblDebug.Text = "Please enter your email address"; } if (atSign == true && comma == true) { emailValid = true; lblDebug.Text = ""; } // Name Vaildation Boolean firstNameValid = true; Boolean lastNamevalid = true; Boolean nameValid = true; if (firstName.Any(char.IsNumber)) { firstNameValid = false; lblDebug.Text = "First Name cannot contain a number"; } if (firstName.Any(char.IsWhiteSpace)) { firstNameValid = false; lblDebug.Text = "First Name cannot contain space"; } if (firstName == "") { firstNameValid = false; lblDebug.Text = "Please enter your first name"; } if (lastName.Any(char.IsNumber)) { lastNamevalid = false; lblDebug.Text = "Last Name cannot contain a number"; } if (lastName.Any(char.IsWhiteSpace)) { lastNamevalid = false; lblDebug.Text = "Last Name cannot contain space"; } if (lastName == "") { lastNamevalid = false; lblDebug.Text = "Please enter your last name"; } if (firstNameValid == false || lastNamevalid == false) { nameValid = false; } // phone number vaildation Boolean phoneNumberValid = true; if (phoneNumber.Length < 10) { phoneNumberValid = false; lblDebug.Text = "Plase enter correct phone number"; } if (phoneNumber.Any(char.IsLetter)) { phoneNumberValid = false; lblDebug.Text = "Phone Number cannot contain letters"; } if (phoneNumber.Any(char.IsWhiteSpace)) { phoneNumberValid = false; lblDebug.Text = "Phone Number cannot contain space"; } if (phoneNumber == "") { phoneNumberValid = false; lblDebug.Text = "Please enter your phone number"; } // Birthday Validation Boolean birthdayValid = true; DateTime bod; if (DateTime.TryParse(birthday, out bod) && (!birthday.Contains('-'))) { String.Format("{0:d/MM/yyyy}", bod); var today = DateTime.Today; DateTime bir = DateTime.ParseExact(tbBirthday.Text, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); var age = today.Year - bir.Year; if (bir.Month > today.Month) { age--; } else if (bir.Day > today.Day) { age--; } if (age >= 130 || age < 18) { birthdayValid = false; lblDebug.Text = "You cannot be older than 130 or younger than 18"; } } else { birthdayValid = false; lblDebug.Text = "Please enter correct format of birthday"; } // State Valid Boolean stateValid = true; if (ddState.SelectedValue == "NO") { stateValid = false; lblDebug.Text = "Please choose your state"; } // City validation Boolean cityValid = true; if (city == "") { lblDebug.Text = "Please enter your city name"; cityValid = false; } if (city.Any(char.IsNumber)) { cityValid = false; lblDebug.Text = "City cannot contains a number"; } // ZIP validation Boolean zipValid = true; if (zip.Any(char.IsLetter)) { zipValid = false; lblDebug.Text = "ZIP Code cannot contains a letter"; } if (zip.Length > 5) { zipValid = false; lblDebug.Text = "Please enter correct format of ZIP Code"; } if (zip == "") { zipValid = false; lblDebug.Text = "Please enter ZIP code"; } if (passwordCorrect == true && passwordValid == true && emailValid == true && nameValid == true && phoneNumberValid == true && birthdayValid == true && stateValid == true && cityValid == true && zipValid == true) { //check the email if it is esist System.Data.SqlClient.SqlCommand check_User_Name = new System.Data.SqlClient.SqlCommand(); check_User_Name.Connection = sc; check_User_Name.CommandText = "SELECT * FROM [RMUser] WHERE ([Email] = @Email);"; check_User_Name.Parameters.AddWithValue("@Email", tbTenantEmail.Text); System.Data.SqlClient.SqlDataReader hostreader = check_User_Name.ExecuteReader(); if (hostreader.HasRows) { //Username exist lblDebug.Text = "User already exist"; } else { //Username doesn't exist. System.Data.SqlClient.SqlCommand insertTest = new System.Data.SqlClient.SqlCommand(); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FirstName", firstName)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@LastName", lastName)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", email)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PhoneNumber", phoneNumber)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@DOB", DOB)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@HouseNum", HouseNumber)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Street", street)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@City", city)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@State", state)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Zip", zip)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ModfiedDate", now)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserType", userType)); insertTest.Connection = sc; hostreader.Close(); insertTest.CommandText = "Insert into [dbo].[RMUser] VALUES (@FirstName," + "@LastName," + "@Email," + "@PhoneNumber," + "@DOB," + "@HouseNum," + "@Street," + "@City," + "@State," + "@Zip," + "@ModfiedDate," + "@UserType);"; insertTest.ExecuteNonQuery(); System.Data.SqlClient.SqlCommand maxID = new System.Data.SqlClient.SqlCommand(); maxID.Connection = sc; maxID.CommandText = "Select MAX(UserID) from [dbo].[RMUser];"; int tempID = (Int32)maxID.ExecuteScalar(); System.Data.SqlClient.SqlCommand insertPass = new System.Data.SqlClient.SqlCommand(); insertPass.Connection = sc; insertPass.CommandText = "Insert into [dbo].[HostPassword] values(@MaxID, @Password, @ModifiedDate, @Email);"; insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@MaxID", tempID)); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", email)); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Password", PasswordHash.HashPassword(tbPassword.Text))); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ModifiedDate", DateTime.Now)); insertPass.ExecuteNonQuery(); lbsuccess.Text = "Registration success!"; Response.Redirect("MasterTenantDash.aspx"); } } }
/// <summary> /// Tarea encargada de ejecutar el proceso HTTP /// </summary> /// <param name="context"></param> private void HttpListenerCallback(HttpListenerContext context) { byte[] respuesta = new byte[0]; String data_text = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd(); try { String[] ruta = context.Request.RawUrl.Split('/'); //La ruta es /fichero/{usuario} y es un POST if (ruta[1].CompareTo("fichero") == 0 && context.Request.HttpMethod.CompareTo("POST") == 0 && ruta.Length == 3) { Logger.Log("Servicio POST fichero iniciado"); byte[] fichero = Convert.FromBase64String(data_text); if (fichero.Length > 5 * 1024 * 1024) { context.Response.StatusCode = 413; context.Response.StatusDescription = "Request Entity Too Large"; RespuestaError re = new RespuestaError() { Error = "El fichero no puede ser más grande de 5 MB" }; respuesta = Funciones.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(re)); } else { FicheroMP3 ficheroMP3 = new FicheroMP3() { Usuario = ruta[2], FechaRecepcion = DateTime.UtcNow, Estado = FicheroMP3.EstadosFicheroMP3.Pendiente, FechaTranscripcion = null, Transcripcion = null }; BD.AddFicheroMP3(ficheroMP3); using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + ficheroMP3.Id + ".mp3", FileMode.Create, FileAccess.Write)) { fs.Write(fichero, 0, fichero.Length); } context.Response.StatusCode = 200; context.Response.StatusDescription = "Ok"; } } //La ruta es /ficheros/{usuario} y es un GET. Los parámetros desde y hasta al ser opcionales no van en formato Friendly, sino en Query Parameters else if (ruta[1].CompareTo("ficheros") == 0 && context.Request.HttpMethod.CompareTo("GET") == 0 && ruta.Length == 3) { Logger.Log("Servicio GET ficheros iniciado"); DateTime?desde = null; DateTime?hasta = null; Boolean paramsOK = true; if (context.Request.QueryString["desde"] != null) { desde = Funciones.CheckParamFecha(context.Request.QueryString["desde"], ref respuesta); if (desde == null) { paramsOK = false; } } if (context.Request.QueryString["hasta"] != null) { hasta = Funciones.CheckParamFecha(context.Request.QueryString["hasta"], ref respuesta); if (hasta == null) { paramsOK = false; } } if (paramsOK) { context.Response.StatusCode = 200; context.Response.StatusDescription = "Ok"; respuesta = Funciones.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(BD.GetLista(ruta[2].Split('?')[0], desde, hasta))); } else { context.Response.StatusCode = 400; context.Response.StatusDescription = "Bad Request"; } } //La ruta es /fichero/{usuario}/{id} y es un GET else if (ruta[1].CompareTo("fichero") == 0 && context.Request.HttpMethod.CompareTo("GET") == 0 && ruta.Length == 4) { Logger.Log("Servicio GET fichero iniciado"); Int32 id; if (Int32.TryParse(ruta[3], out id)) { RespuestaTranscripcion rt = BD.GetTranscripcion(ruta[2], id); if (rt.Codigo == 0) { context.Response.StatusCode = 200; context.Response.StatusDescription = "Ok"; respuesta = Funciones.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(rt)); } else if (rt.Codigo == -1) { context.Response.StatusCode = 404; context.Response.StatusDescription = "Not Found"; } else if (rt.Codigo == -2) { context.Response.StatusCode = 410; context.Response.StatusDescription = "Gone"; } else { context.Response.StatusCode = 204; context.Response.StatusDescription = "No Content"; } } else { context.Response.StatusCode = 400; context.Response.StatusDescription = "Bad Request"; } } //Cualquier otro caso la ruta no existe y se devuelve Not Found. else { context.Response.StatusCode = 404; context.Response.StatusDescription = "Not Found"; } } catch (System.Exception ex) { //Si se produce una excepción se devuelve un Internal Server Error (500) context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; respuesta = Funciones.GetBytes(ex.ToString()); } context.Response.ContentLength64 = respuesta.Length; context.Response.OutputStream.Write(respuesta, 0, respuesta.Length); context.Response.Close(); }
/// <summary> /// 设置标题栏边距 /// </summary> /// <param name="element"></param> /// <param name="value"></param> public static void SetKeepMaximized(DependencyObject element, Boolean value) => element.SetValue(KeepMaximizedProperty, value);
// file force saving process public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress) { if (fileData["url"].Equals(null)) { throw new Exception("DownloadUrl is null"); } var downloadUri = (string)fileData["url"]; string curExt = Path.GetExtension(fileName).ToLower(); // get current file extension var downloadExt = fileData.ContainsKey("filetype") ? "." + (string)fileData["filetype"] : Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0 Boolean newFileName = false; // convert downloaded file to the file with the current extension if these extensions aren't equal if (!curExt.Equals(downloadExt)) { try { // convert file and give url to a new file string newFileUri; var result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri); if (string.IsNullOrEmpty(newFileUri)) { newFileName = true; } else { downloadUri = newFileUri; } } catch (Exception) { newFileName = true; } } _Default.VerifySSL(); string forcesavePath = ""; Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm if (isSubmitForm) // if the form is submitted { if (newFileName) { fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists } else { fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress); } forcesavePath = _Default.StoragePath(fileName, userAddress); } else { if (newFileName) { fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress); } forcesavePath = _Default.ForcesavePath(fileName, userAddress, false); if (forcesavePath.Equals("")) // create forcesave path if it doesn't exist { forcesavePath = _Default.ForcesavePath(fileName, userAddress, true); } } DownloadToFile(downloadUri, forcesavePath); if (isSubmitForm) { var jss = new JavaScriptSerializer(); var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"])); var action = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0])); var user = action["userid"].ToString(); // get the user id DocEditor.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file } return(0); }
private void im_MouseDown(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { mPagePaper._Control_press = true; for (int i = 0; i < vImages.Count; i++) { if (vImages[i].Equals(sender)) { if (mPagePaper.line_num_count < 6 ) //前五道题答案提示 { //mPagePaper.t_Display.Stop(); mPagePaper.tip_display.Visibility = System.Windows.Visibility.Visible; if (_full != null) _full.Visibility = Visibility.Hidden; _full = mBorders[i]; mBorders[i].Visibility = Visibility.Visible; //显示通用 _control = true; //显示通用 opt = (i + 1).ToString();//被试选择答案 PapertestCanvas.IsEnabled = false; if (mPagePaper.correct_ans != opt ) { mPagePaper.tip_display.Foreground = Brushes.Red; mPagePaper.tip_display.Content = "选择错误,正确答案为:" + mPagePaper.correct_ans; if (mPagePaper.re_count_num<2) mPagePaper.recede_control = true; } else { //mPagePaper.t_Display.Stop(); mPagePaper.tip_display.Foreground = new SolidColorBrush(Color.FromRgb(0, 255, 0)); mPagePaper.tip_display.Content = "正 确"; } //mPagePaper.t_Display.Stop(); //mPagePaper._flash_Display.Stop(); } else if (mPagePaper.line_num_count >= 6) { mPagePaper.tip_display.Foreground = Brushes.Black; //mPagePaper.t_Display.Stop(); mPagePaper.tip_display.Foreground = Brushes.Red; /*******************用于选择多次****************************/ if (_full != null) _full.Visibility = Visibility.Hidden; _full = mBorders[i]; /***********************************************/ mBorders[i].Visibility = Visibility.Visible; //显示通用 _control = true; //显示通用 /******************************用于写文件*********************************/ opt = (i + 1).ToString(); /*************************************************************************/ ///////////////////////////实验开始///////////// //if (mPagePaper.correct_ans != opt) //{ // mPagePaper.tip_display.Content = "选择错误,正确答案为:" + mPagePaper.correct_ans; // if (mPagePaper.re_count_num < 2) mPagePaper.recede_control = true; //} //else //{ // mPagePaper.tip_display.Content = "恭喜你,答对了!"; //} ////////////////////实验结束////////////// } } } } }
private void DoLoadSubtitle(Subtitle subtitle, List<string> lines) { //—Peter. //—Estoy de licencia. //01:48:50.07\01:48:52.01 var sb = new StringBuilder(); Paragraph p = null; subtitle.Paragraphs.Clear(); foreach (string line in lines) { string s = line.Trim(); if (regexTimeCodes.IsMatch(s)) { // Start and end time separated by "\" var temp = s.Split('\\'); if (temp.Length > 1) { string start = temp[0]; string end = temp[1]; string[] startParts = start.Split(new[] { ':', '.' }, StringSplitOptions.RemoveEmptyEntries); string[] endParts = end.Split(new[] { ':', '.' }, StringSplitOptions.RemoveEmptyEntries); if (startParts.Length == 4 && endParts.Length == 4) { try { p = new Paragraph(); p.StartTime = DecodeTimeCode(startParts); p.EndTime = DecodeTimeCode(endParts); string text = sb.ToString().Trim(); Boolean positionTop = false; // If text starts with "}", subtitle appears at the top if (text.StartsWith('}')) { positionTop = true; // Remove the tag "}" text = text.Remove(0, 1); } // Replace tags text = text.Replace("[", @"<i>"); text = text.Replace("]", @"</i>"); // Split subtitle lines (one subtitle has one or more lines) var subtitleLines = text.SplitToLines(); int count = 0; var lineSb = new StringBuilder(); string tempLine = string.Empty; foreach (string subtitleLine in subtitleLines) { // Append line break in every line except the first one if (count > 0) lineSb.Append(Environment.NewLine); tempLine = subtitleLine; // Close italics in every line (if next line is in italics, SoftNI will use "[" at the beginning) if (Utilities.CountTagInText(tempLine, "<i>") > Utilities.CountTagInText(tempLine, "</i>")) tempLine = tempLine + "</i>"; lineSb.Append(tempLine); count++; } text = lineSb.ToString(); // Replace "</i>line break<i>" with just a line break (SubRip does not need to close italics and open them again in the next line). text = text.Replace("</i>" + Environment.NewLine + "<i>", Environment.NewLine); // Subtitle appears at the top (add tag) if (positionTop) text = "{\\an8}" + text; p.Text = text; if (text.Length > 0) subtitle.Paragraphs.Add(p); sb = new StringBuilder(); } catch (Exception exception) { _errorCount++; System.Diagnostics.Debug.WriteLine(exception.Message); } } } } else if (string.IsNullOrWhiteSpace(line) || line.StartsWith('*')) { // skip empty lines or start } else if (p != null) { sb.AppendLine(line); } } subtitle.Renumber(); }
protected override void StoreFriendships(UUID agentID, UUID friendID) { Boolean agentIsLocal = true; Boolean friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); } // Are they both local users? if (agentIsLocal && friendIsLocal) { // local grid users m_log.DebugFormat("[HGFRIENDS MODULE]: Users are both local"); DeletePreviousHGRelations(agentID, friendID); base.StoreFriendships(agentID, friendID); return; } // ok, at least one of them is foreigner, let's get their data IClientAPI agentClient = LocateClientObject(agentID); IClientAPI friendClient = LocateClientObject(friendID); AgentCircuitData agentClientCircuit = null; AgentCircuitData friendClientCircuit = null; string agentUUI = string.Empty; string friendUUI = string.Empty; string agentFriendService = string.Empty; string friendFriendService = string.Empty; if (agentClient != null) { agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode); agentUUI = Util.ProduceUserUniversalIdentifier(agentClientCircuit); agentFriendService = agentClientCircuit.ServiceURLs["FriendsServerURI"].ToString(); RecacheFriends(agentClient); } if (friendClient != null) { friendClientCircuit = ((Scene)(friendClient.Scene)).AuthenticateHandler.GetAgentCircuitData(friendClient.CircuitCode); friendUUI = Util.ProduceUserUniversalIdentifier(friendClientCircuit); friendFriendService = friendClientCircuit.ServiceURLs["FriendsServerURI"].ToString(); RecacheFriends(friendClient); } m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}", agentUUI, friendUUI, agentFriendService, friendFriendService); // Generate a random 8-character hex number that will sign this friendship string secret = UUID.Random().ToString().Substring(0, 8); string theFriendUUID = friendUUI + ";" + secret; string agentUUID = agentUUI + ";" + secret; if (agentIsLocal) // agent is local, 'friend' is foreigner { // This may happen when the agent returned home, in which case the friend is not there // We need to look for its information in the friends list itself FriendInfo[] finfos = null; bool confirming = false; if (friendUUI == string.Empty) { finfos = GetFriendsFromCache(agentID); foreach (FriendInfo finfo in finfos) { if (finfo.TheirFlags == -1) { if (finfo.Friend.StartsWith(friendID.ToString())) { friendUUI = finfo.Friend; theFriendUUID = friendUUI; UUID utmp = UUID.Zero; string url = String.Empty; string first = String.Empty; string last = String.Empty; // If it's confirming the friendship, we already have the full UUI with the secret if (Util.ParseUniversalUserIdentifier(theFriendUUID, out utmp, out url, out first, out last, out secret)) { agentUUID = agentUUI + ";" + secret; m_uMan.AddUser(utmp, first, last, url); } confirming = true; break; } } } if (!confirming) { friendUUI = m_uMan.GetUserUUI(friendID); theFriendUUID = friendUUI + ";" + secret; } friendFriendService = m_uMan.GetUserServerURL(friendID, "FriendsServerURI"); // m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}", // agentUUI, friendUUI, agentFriendService, friendFriendService); } // Delete any previous friendship relations DeletePreviousRelations(agentID, friendID); // store in the local friends service a reference to the foreign friend FriendsService.StoreFriend(agentID.ToString(), theFriendUUID, 1); // and also the converse FriendsService.StoreFriend(theFriendUUID, agentID.ToString(), 1); //if (!confirming) //{ // store in the foreign friends service a reference to the local agent HGFriendsServicesConnector friendsConn = null; if (friendClientCircuit != null) // the friend is here, validate session { friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID); } else // the friend is not here, he initiated the request in his home world { friendsConn = new HGFriendsServicesConnector(friendFriendService); } friendsConn.NewFriendship(friendID, agentUUID); //} } else if (friendIsLocal) // 'friend' is local, agent is foreigner { // Delete any previous friendship relations DeletePreviousRelations(agentID, friendID); // store in the local friends service a reference to the foreign agent FriendsService.StoreFriend(friendID.ToString(), agentUUI + ";" + secret, 1); // and also the converse FriendsService.StoreFriend(agentUUI + ";" + secret, friendID.ToString(), 1); if (agentClientCircuit != null) { // store in the foreign friends service a reference to the local agent HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID); friendsConn.NewFriendship(agentID, friendUUI + ";" + secret); } } else // They're both foreigners! { HGFriendsServicesConnector friendsConn; if (agentClientCircuit != null) { friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID); friendsConn.NewFriendship(agentID, friendUUI + ";" + secret); } if (friendClientCircuit != null) { friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID); friendsConn.NewFriendship(friendID, agentUUI + ";" + secret); } } // my brain hurts now }
public override string ToText(Subtitle subtitle, string title) { var sb = new StringBuilder(); sb.AppendLine("*PART 1*"); sb.AppendLine("00:00:00:00\\00:00:00:00"); foreach (Paragraph p in subtitle.Paragraphs) { string text = p.Text; bool positionTop = false; // If text starts with {\an8}, subtitle appears at the top if (text.StartsWith("{\\an8}")) { positionTop = true; // Remove the tag {\an8}. text = text.Remove(0, 6); } // Split lines (split a subtitle into its lines) var lines = text.SplitToLines(); int count = 0; var lineSb = new StringBuilder(); string tempLine = string.Empty; Boolean nextLineInItalics = false; foreach (string line in lines) { // Append line break in every line except the first one if (count > 0) lineSb.Append(Environment.NewLine); tempLine = line; // This line should be in italics (it was detected in previous line) if (nextLineInItalics) { tempLine = "<i>" + tempLine; nextLineInItalics = false; } if (tempLine.StartsWith("<i>") && tempLine.EndsWith("</i>")) { // Whole line is in italics // Remove <i> from the beginning tempLine = tempLine.Remove(0, 3); // Remove </i> from the end tempLine = tempLine.Remove(tempLine.Length - 4, 4); // Add new italics tag at the beginning tempLine = "[" + tempLine; } else if (tempLine.StartsWith("<i>") && Utilities.CountTagInText(tempLine, "<i>") > Utilities.CountTagInText(tempLine, "</i>")) { // Line starts with <i> but italics are not closed. So the next line should be in italics nextLineInItalics = true; } lineSb.Append(tempLine); count++; text = lineSb.ToString(); // Replace remaining italics tags text = text.Replace("<i>", @"["); text = text.Replace("</i>", @"]"); text = HtmlUtil.RemoveHtmlTags(text); } // Add top-position SoftNI marker "}" at the beginning of first line. if (positionTop) text = "}" + text; sb.AppendLine(string.Format("{0}{1}{2}\\{3}", text, Environment.NewLine, p.StartTime.ToHHMMSSPeriodFF().Replace(".", ":"), p.EndTime.ToHHMMSSPeriodFF().Replace(".", ":"))); } sb.AppendLine(@"*END*"); sb.AppendLine(@"...........\..........."); sb.AppendLine(@"*CODE*"); sb.AppendLine(@"0000000000000000"); sb.AppendLine(@"*CAST*"); sb.AppendLine(@"*GENERATOR*"); sb.AppendLine(@"*FONTS*"); sb.AppendLine(@"*READ*"); sb.AppendLine(@"0,300 15,000 130,000 100,000 25,000"); sb.AppendLine(@"*TIMING*"); sb.AppendLine(@"1 25 0"); sb.AppendLine(@"*TIMED BACKUP NAME*"); sb.AppendLine(@"C:\"); sb.AppendLine(@"*FORMAT SAMPLE ÅåÉéÌìÕõÛûÿ*"); sb.AppendLine(@"*READ ADVANCED*"); sb.AppendLine(@"< > 1 1 0,300"); sb.AppendLine(@"*MARKERS*"); return sb.ToString(); }
public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context) { ErpPage currentPage = null; try { #region << Init >> if (context.Node == null) { return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component"))); } var pageFromModel = context.DataModel.GetProperty("Page"); if (pageFromModel == null) { return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null"))); } else if (pageFromModel is ErpPage) { currentPage = (ErpPage)pageFromModel; } else { return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type"))); } var baseOptions = InitPcFieldBaseOptions(context); var options = PcFieldTextareaOptions.CopyFromBaseOptions(baseOptions); if (context.Options != null) { options = JsonConvert.DeserializeObject <PcFieldTextareaOptions>(context.Options.ToString()); } var modelFieldLabel = ""; var model = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel); if (String.IsNullOrWhiteSpace(options.LabelText)) { options.LabelText = modelFieldLabel; } ViewBag.LabelMode = options.LabelMode; ViewBag.Mode = options.Mode; if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined) { ViewBag.LabelMode = baseOptions.LabelMode; } if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined) { ViewBag.Mode = baseOptions.Mode; } var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName); var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as FieldAccess?; if (accessOverride != null) { model.Access = accessOverride.Value; } var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?; if (requiredOverride != null) { model.Required = requiredOverride.Value; } else { if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs)) { if (options.RequiredOverrideDs.ToLowerInvariant() == "true") { model.Required = true; } else if (options.RequiredOverrideDs.ToLowerInvariant() == "false") { model.Required = false; } } } #endregion ViewBag.Options = options; ViewBag.Model = model; ViewBag.Node = context.Node; ViewBag.ComponentMeta = componentMeta; ViewBag.RequestContext = ErpRequestContext; ViewBag.AppContext = ErpAppContext.Current; if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help) { var isVisible = true; var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible); if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString())) { if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool)) { isVisible = outBool; } } else if (isVisibleDS is Boolean) { isVisible = (bool)isVisibleDS; } ViewBag.IsVisible = isVisible; model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value); } switch (context.Mode) { case ComponentMode.Display: return(await Task.FromResult <IViewComponentResult>(View("Display"))); case ComponentMode.Design: return(await Task.FromResult <IViewComponentResult>(View("Design"))); case ComponentMode.Options: return(await Task.FromResult <IViewComponentResult>(View("Options"))); case ComponentMode.Help: return(await Task.FromResult <IViewComponentResult>(View("Help"))); default: ViewBag.Error = new ValidationException() { Message = "Unknown component mode" }; return(await Task.FromResult <IViewComponentResult>(View("Error"))); } } catch (ValidationException ex) { ViewBag.Error = ex; return(await Task.FromResult <IViewComponentResult>(View("Error"))); } catch (Exception ex) { ViewBag.Error = new ValidationException() { Message = ex.Message }; return(await Task.FromResult <IViewComponentResult>(View("Error"))); } }
protected override bool DeleteFriendship(UUID agentID, UUID exfriendID) { Boolean agentIsLocal = true; Boolean friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); friendIsLocal = UserManagementModule.IsLocalGridUser(exfriendID); } // Are they both local users? if (agentIsLocal && friendIsLocal) { // local grid users return(base.DeleteFriendship(agentID, exfriendID)); } // ok, at least one of them is foreigner, let's get their data string agentUUI = string.Empty; string friendUUI = string.Empty; if (agentIsLocal) // agent is local, 'friend' is foreigner { // We need to look for its information in the friends list itself FriendInfo[] finfos = GetFriendsFromCache(agentID); FriendInfo finfo = GetFriend(finfos, exfriendID); if (finfo != null) { friendUUI = finfo.Friend; // delete in the local friends service the reference to the foreign friend FriendsService.Delete(agentID, friendUUI); // and also the converse FriendsService.Delete(friendUUI, agentID.ToString()); // notify the exfriend's service Util.FireAndForget( delegate { Delete(exfriendID, agentID, friendUUI); }, null, "HGFriendsModule.DeleteFriendshipForeignFriend"); m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentID, friendUUI); return(true); } } else if (friendIsLocal) // agent is foreigner, 'friend' is local { agentUUI = GetUUI(exfriendID, agentID); if (agentUUI != string.Empty) { // delete in the local friends service the reference to the foreign agent FriendsService.Delete(exfriendID, agentUUI); // and also the converse FriendsService.Delete(agentUUI, exfriendID.ToString()); // notify the agent's service? Util.FireAndForget( delegate { Delete(agentID, exfriendID, agentUUI); }, null, "HGFriendsModule.DeleteFriendshipLocalFriend"); m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentUUI, exfriendID); return(true); } } //else They're both foreigners! Can't handle this return(false); }
public Ramka() { zajęta = false; }
public User(int idUser, String name, DateTime birthday, DateTime since, String image, List <Score> scores, String aboutMe, Boolean erase) { this.idUser = idUser; this.name = name; this.birthday = birthday; this.aboutMe = aboutMe; this.since = since; this.image = image; this.scores = scores; }
public FR_Base Remove(DbConnection Connection, DbTransaction Transaction, string ConnectionString) { this.IsDeleted = true; return this.Save(Connection, Transaction, ConnectionString); }
public long Verify_AdminUser(ref object Common, ref object MyLogix) { String Authtoken = ""; String MyURI; String TransferKey = ""; Boolean Debug = false; if (AdminUserID != 0) { if (Debug) { lCommon.Write_Log("auth.txt", "AppName=" + lCommon.AppName + " - Verify_AdminUser was called, but we already know the AdminUserID=" + AdminUserID, true); } //'we already know who the AdminUser is ... we shouldn't be looking him up more than once Object o = lCommon; lLogix.Load_Roles(ref o, AdminUserID); return(AdminUserID); } //'1st, check the transferkey and see if the user is being transferred into AMS from another product (PrefMan) if (GetCgiValue("transferkey") != String.Empty) { if (Debug) { lCommon.Write_Log("auth.txt", "AppName=" + lCommon.AppName + " - Checking the TransferKey (" + GetCgiValue("transferkey") + ") AdminUserID=" + AdminUserID, true); } TransferKey = GetCgiValue("transferkey"); AdminUserID = lLogix.Auth_TransferKey_Verify(ref lCommon, TransferKey, ref AdminName, ref LanguageID, ref Authtoken); if (Debug) { lCommon.Write_Log("auth.txt", "AppName=" + lCommon.AppName + " - After TransferKey_Verify AdminUserID=" + AdminUserID, true); } if (AdminUserID != 0) { Response.Cookies["AuthToken"].Value = Authtoken; Object o = lCommon; lLogix.Load_Roles(ref o, AdminUserID); return(AdminUserID); } } else { } Authtoken = ""; if (Request.Cookies["AuthToken"] != null) { Authtoken = Request.Cookies["AuthToken"].Value; } if (Debug) { lCommon.Write_Log("auth.txt", "AppName=" + lCommon.AppName + " - AuthToken='" + Authtoken + "' Transferkey='" + GetCgiValue("transferkey") + "'", true); } AdminUserID = 0; AdminUserID = lLogix.Auth_Token_Verify(ref lCommon, Authtoken, ref AdminName, ref LanguageID); if (Debug) { lCommon.Write_Log("auth.txt", "AppName=" + lCommon.AppName + " - After checking AuthToken, AdminUserID=" + AdminUserID, true); } if (AdminUserID == 0) { MyURI = System.Web.HttpUtility.UrlEncode(Request.Url.AbsoluteUri); /* * Send("<!DOCTYPE html ") * Send(" PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN""") * Send(" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">") * Send("<html xmlns=""http://www.w3.org/1999/xhtml"">") * Send("<head>") * Send("<meta http-equiv=""refresh"" content=""0; url=/logix/login.aspx?mode=invalid&bounceback=" & MyURI & """ />") * Send("<title>Logix</title>") * Send("</head>") * Send("<body bgcolor=""#ffffff"">") * Send("<!-- Bouncing -->") * Send("</body>") * Send("</html>") * Response.End()*/ } else { Object o = lCommon; lLogix.Load_Roles(ref o, AdminUserID); } return(AdminUserID); }
private void btn_save_Click(object sender, EventArgs e) { Boolean success = false, ok = false; String notificationText = ""; z_Notification notify = new z_Notification(); String branch = GlobalClass.branch; String col = "", val = ""; String notifyadd = null, id = ""; String table = "hr_leave_type"; String code = "", description = ""; if (String.IsNullOrEmpty(txt_code.Text)) { MessageBox.Show("Please enter the required fields."); return; } if(String.IsNullOrEmpty(txt_description.Text)) { MessageBox.Show("Please enter the required fields."); return; } code = txt_code.Text; description = txt_description.Text; if(isnew) { col = "code,description"; val = "" + db.str_E(code) + "," + db.str_E(description) + ""; db.DeleteOnTable(table, "code=" + db.str_E(code) + " AND cancel='Y'"); if (db.InsertOnTable(table, col, val)) { success = true; } else { success = false; //db.DeleteOnTable(table, "code='" + code + "'"); MessageBox.Show("Failed on saving."); } } else { col = "description=" + db.str_E(description) + ""; if (db.UpdateOnTable(table, col, "code=" + db.str_E(code) + "")) { success = true; } else { success = false; MessageBox.Show("Failed on saving."); } } if(success) { goto_win1(); ClearForm(); disp_list(); } }
public GeneralOptions LoadOptions() { using (var key = OpenOptionsKey()) { int debugEnabledInConfig = ((Hierarchy)LogManager.GetRepository()).Root.Level == Level.Debug ? 1 : 0; return(new GeneralOptions() { ShouldCheckForNewerVersions = (int)(key.GetValue(ValueNameShouldCheckForNewerVersions) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["checkForNewerVersions"] ?? bool.TrueString))) != 0, CheckIfOnline = (int)(key.GetValue(ValueNameCheckIfOnline) ?? 1) != 0, StoreAppDataInRoamingFolder = (int)(key.GetValue(ValueNameStoreAppDataInRoamingFolder) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["storeAppDataInRoamingFolder"] ?? bool.FalseString))) != 0, DisableCertificateValidation = (int)(key.GetValue(ValueNameDisableCertificateValidation) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["disableCertificateValidation"] ?? bool.FalseString))) != 0, EnableClientCertificate = (int)(key.GetValue(ValueNameEnableClientCertificate) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["enableClientCertificate"] ?? bool.FalseString))) != 0, EnableTls12 = (int)(key.GetValue(ValueNameEnableTls12) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["enableTls12"] ?? bool.TrueString))) != 0, EnableSsl3 = (int)(key.GetValue(ValueNameEnableSsl3) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["enableSsl3"] ?? bool.FalseString))) != 0, CalDavConnectTimeout = TimeSpan.Parse((string)(key.GetValue(ValueNameCalDavConnectTimeout) ?? ConfigurationManager.AppSettings["caldavConnectTimeout"] ?? "01:30")), FixInvalidSettings = (int)(key.GetValue(ValueNameFixInvalidSettings) ?? 1) != 0, IncludeCustomMessageClasses = (int)(key.GetValue(ValueNameIncludeCustomMessageClasses) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["includeCustomMessageClasses"] ?? bool.FalseString))) != 0, LogReportsWithoutWarningsOrErrors = (int)(key.GetValue(ValueNameLogReportsWithoutWarningsOrErrors) ?? 0) != 0, IncludeEntityReportsWithoutErrorsOrWarnings = (int)(key.GetValue(ValueNameIncludeEntityReportsWithoutErrorsOrWarnings) ?? 0) != 0, LogEntityNames = (int)(key.GetValue(ValueNameLogEntityNames) ?? 0) != 0, LogReportsWithWarnings = (int)(key.GetValue(ValueNameLogReportsWithWarnings) ?? 1) != 0, ShowReportsWithWarningsImmediately = (int)(key.GetValue(ValueNameShowReportsWithWarningsImmediately) ?? 0) != 0, ShowReportsWithErrorsImmediately = (int)(key.GetValue(ValueNameShowReportsWithErrorsImmediately) ?? 1) != 0, MaxReportAgeInDays = (int)(key.GetValue(ValueNameMaxReportAgeInDays) ?? 1), EnableDebugLog = (int)(key.GetValue(ValueNameEnableDebugLog) ?? debugEnabledInConfig) != 0, EnableTrayIcon = (int)(key.GetValue(ValueNameEnableTrayIcon) ?? 1) != 0, AcceptInvalidCharsInServerResponse = (int)(key.GetValue(ValueNameAcceptInvalidCharsInServerResponse) ?? 0) != 0, UseUnsafeHeaderParsing = (int)(key.GetValue(ValueNameUseUnsafeHeaderParsing) ?? Convert.ToInt32(SystemNetSettings.UseUnsafeHeaderParsing)) != 0, TriggerSyncAfterSendReceive = (int)(key.GetValue(ValueNameTriggerSyncAfterSendReceive) ?? 0) != 0, ExpandAllSyncProfiles = (int)(key.GetValue(ValueNameExpandAllSyncProfiles) ?? 1) != 0, EnableAdvancedView = (int)(key.GetValue(ValueNameEnableAdvancedView) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["enableAdvancedView"] ?? bool.FalseString))) != 0, QueryFoldersJustByGetTable = (int)(key.GetValue(ValueNameQueryFoldersJustByGetTable) ?? 1) != 0, ShowProgressBar = (int)(key.GetValue(ValueNameShowProgressBar) ?? Convert.ToInt32(Boolean.Parse(ConfigurationManager.AppSettings["showProgressBar"] ?? bool.TrueString))) != 0, ThresholdForProgressDisplay = (int)(key.GetValue(ValueNameThresholdForProgressDisplay) ?? int.Parse(ConfigurationManager.AppSettings["loadOperationThresholdForProgressDisplay"] ?? "50")), MaxSucessiveWarnings = (int)(key.GetValue(ValueNameMaxSucessiveWarnings) ?? 2) }); } }
static Boolean load; /// Set to true if patient is to be loaded after form closes // ------------------------------------------------------------------------------------------------- public static int ShowDialog() { load = false; // ------------------------------------------------------------------------------------------------- // INIT FORM // ------------------------------------------------------------------------------------------------- Form prompt = new Form() { Width = width, Height = height, FormBorderStyle = FormBorderStyle.FixedDialog, Text = "Select Patient to Load", StartPosition = FormStartPosition.CenterScreen }; ListView listView1 = new ListView(); // ------------------------------------------------------------------------------------------------- // SET DIMENSIONS // ------------------------------------------------------------------------------------------------- numEntries = Form1.PatientList.Count; if (numEntries <= maxLinesNoScrollBar) { scrollBarWidth = 0; } listView1.Width = width - scrollBarWidth; listView1.Height = height - headerHeight - buttonHeight - (2 * marginButtonsVertical); colDateWidth = (((listView1.Width) / 8) * 2) - (scrollBarWidth / 3); colNameWidth = (((listView1.Width) / 8) * 5) - (scrollBarWidth / 3); colSexWidth = (((listView1.Width) / 8) * 1) - (scrollBarWidth / 3); marginButtonsHorz = (width - (2 * buttonWidth)) / 3; // ------------------------------------------------------------------------------------------------- // SET LIST VIEW PROPERTIES // ------------------------------------------------------------------------------------------------- listView1.Scrollable = true; listView1.View = View.Details; // Set the view to show details. listView1.LabelEdit = true; // Allow the user to edit item text. listView1.AllowColumnReorder = true; // Allow the user to rearrange columns. listView1.FullRowSelect = true; // Select the item and subitems when selection is made. listView1.GridLines = true; listView1.Sorting = SortOrder.Ascending; listView1.MultiSelect = false; listView1.LabelEdit = false; // ------------------------------------------------------------------------------------------------- // ADD ITEMS TO LIST VIEW // ------------------------------------------------------------------------------------------------- listView1.Columns.Add("Date", colDateWidth, HorizontalAlignment.Left); listView1.Columns.Add("Name", colNameWidth, HorizontalAlignment.Left); listView1.Columns.Add("M/F", colSexWidth, HorizontalAlignment.Left); for (int i = Form1.PatientList.Count - 1; i >= 0; i--) { AddItem(listView1, Form1.PatientList[i]); } // ------------------------------------------------------------------------------------------------- // BUTTONS & CLICKS // ------------------------------------------------------------------------------------------------- //Console.WriteLine("listView height = " + listView1.Height + "; marginButtonHorz = " + marginButtonsHorz + "; y = " + (height - buttonHeight - marginButtonsVertical)); Button cancel = new Button() { Text = "Cancel", Left = marginButtonsHorz, Height = buttonHeight, Width = buttonWidth, Top = height - buttonHeight - marginButtonsVertical - headerHeight }; cancel.Click += (sender, e) => { prompt.Close(); }; Button confirmation = new Button() { Text = "Load", Left = buttonWidth + (2 * marginButtonsHorz), Height = buttonHeight, Width = buttonWidth, Top = height - buttonHeight - marginButtonsVertical - headerHeight }; confirmation.Click += (sender, e) => { load = true; prompt.Close(); }; listView1.DoubleClick += delegate { load = true; prompt.Close(); }; // ------------------------------------------------------------------------------------------------- // ADD ITEMS TO FORM // ------------------------------------------------------------------------------------------------- prompt.Controls.Add(listView1); prompt.Controls.Add(confirmation); prompt.Controls.Add(cancel); prompt.ShowDialog(); return((listView1.SelectedIndices.Count > 0 && load)? listView1.SelectedIndices[0] : -1); }
private FR_Base Load(DbConnection Connection, DbTransaction Transaction, Guid ObjectID, string ConnectionString) { //Standard return type FR_Base retStatus = new FR_Base(); bool cleanupConnection = false; bool cleanupTransaction = false; try { #region Verify/Create Connections //Create connection if Connection is null if(Connection == null) { cleanupConnection = true; Connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(ConnectionString); Connection.Open(); } //If transaction is not open/not valid if(Transaction == null) { cleanupTransaction = true; Transaction = Connection.BeginTransaction(); } #endregion //Get the SelectQuerry string SelectQuery = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CL1_CMN_BPT.CMN_BPT_Supplier.SQL.Select.sql")).ReadToEnd(); DbCommand command = Connection.CreateCommand(); //Set Connection/Transaction command.Connection = Connection; command.Transaction = Transaction; //Set Query/Timeout command.CommandText = SelectQuery; command.CommandTimeout = QueryTimeout; //Firstly, before loading, set the GUID to empty //So the entity does not exist, it will have a GUID set to empty _CMN_BPT_SupplierID = Guid.Empty; CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command,"CMN_BPT_SupplierID", ObjectID ); #region Command Execution try { var loader = new CSV2Core_MySQL.Dictionaries.MultiTable.Loader.DictionaryLoader(Connection,Transaction); var reader = new CSV2Core_MySQL.Support.DBSQLReader(command.ExecuteReader()); reader.SetOrdinals(new string[] { "CMN_BPT_SupplierID","Ext_BusinessParticipant_RefID","SupplierType_RefID","ExternalSupplierProvidedIdentifier","Creation_Timestamp","Tenant_RefID","IsDeleted" }); if (reader.HasRows == true) { reader.Read(); //Single result only //0:Parameter CMN_BPT_SupplierID of type Guid _CMN_BPT_SupplierID = reader.GetGuid(0); //1:Parameter Ext_BusinessParticipant_RefID of type Guid _Ext_BusinessParticipant_RefID = reader.GetGuid(1); //2:Parameter SupplierType_RefID of type Guid _SupplierType_RefID = reader.GetGuid(2); //3:Parameter ExternalSupplierProvidedIdentifier of type String _ExternalSupplierProvidedIdentifier = reader.GetString(3); //4:Parameter Creation_Timestamp of type DateTime _Creation_Timestamp = reader.GetDate(4); //5:Parameter Tenant_RefID of type Guid _Tenant_RefID = reader.GetGuid(5); //6:Parameter IsDeleted of type Boolean _IsDeleted = reader.GetBoolean(6); } //Close the reader so other connections can use it reader.Close(); loader.Load(); if(_CMN_BPT_SupplierID != Guid.Empty){ //Successfully loaded Status_IsAlreadySaved = true; Status_IsDirty = false; } else { //Fault in loading due to invalid UUID (Guid) Status_IsAlreadySaved = false; Status_IsDirty = false; } } catch (Exception ex) { throw; } #endregion #region Cleanup Transaction/Connection //If we started the transaction, we will commit it if (cleanupTransaction && Transaction!= null) Transaction.Commit(); //If we opened the connection we will close it if (cleanupConnection && Connection != null) Connection.Close(); #endregion } catch (Exception ex) { try { if (cleanupTransaction == true && Transaction != null) Transaction.Rollback(); } catch { } try { if (cleanupConnection == true && Connection != null) Connection.Close(); } catch { } throw; } return retStatus; }
public List <LeafNodeDictionaryEntry> GetAndRemoveByXPathContains(List <String> XPathToRemove, Boolean DoRemove = true, Boolean Inverse = false) { List <LeafNodeDictionaryEntry> output = new List <LeafNodeDictionaryEntry>(); List <String> ToRemove = new List <string>(); foreach (var item in items.ToList()) { if (item.XPath.ContainsAny(XPathToRemove) == !Inverse) { ToRemove.Add(item.XPath); output.Add(item); } } if (DoRemove) { RemoveEntriesByXPath(ToRemove); RebuildIndex(); } return(output); }
private void OnBeginEffect(UnityEventArgs<FXArgs> p_args) { m_Args = p_args.EventArgs; m_BeginEffect = true; m_FXplayed = false; }
protected void EnviromentSelection(List<MoChromosome> pop) { List<MoChromosome> result = new List<MoChromosome>(); //List<List<MoChromosome>> dominatedSet0 = NSGA.fastNonDominatedSort(pop); List<List<MoChromosome>> dominatedSet0 = NSGA.FastConstrainedNonDominatedSort(pop); int cnt = 0; while (result.Count() + dominatedSet0[cnt].Count() <= this.popsize) { for (int r = 0; r < dominatedSet0[cnt].Count(); r++) { dominatedSet0[cnt][r].selected = true; } result.AddRange(dominatedSet0[cnt]); cnt++; } if (result.Count() == this.popsize) { mainpop.Clear(); mainpop.AddRange(result); return; } if(this.ItrCounter < Mr * this.TotalItrNum) { UpdateSD(pop); UpdateDintercept(); } List<List<MoChromosome>> associatedSolution = Clustering(dominatedSet0[cnt]); for (int i = 0; i < this.weights.Count(); i++) { associatedSolution[i].Sort(); } cnt = 0; while (true) { int size = 0; for (int i = 0; i < this.weights.Count(); i++) { if (associatedSolution[i].Count() > cnt) { size++; } } if (result.Count() + size <= this.popsize) { for (int i = 0; i < this.weights.Count(); i++) { if (associatedSolution[i].Count() > cnt) { result.Add(associatedSolution[i][cnt]); } } } else { break; } if (result.Count() == this.popsize) break; cnt++; } if (result.Count() < this.popsize) { List<MoChromosome> temp = new List<MoChromosome>(); for (int i = 0; i < this.weights.Count(); i++) { if (associatedSolution[i].Count() > cnt) { temp.Add(associatedSolution[i][cnt]); } } Boolean[] flag = new Boolean[temp.Count()]; for (int i = 0; i < flag.Length; i++) flag[i] = false; while (result.Count() < popsize) { int pos = random.Next(temp.Count()); while (flag[pos] == true) { pos = random.Next(temp.Count()); } flag[pos] = true; result.Add(temp[pos]); } } mainpop.Clear(); mainpop.AddRange(result); return; }
public List <LeafNodeDictionaryEntry> GetAndRemoveByXPathRoot(String XPathRoot, Boolean DoRemove = true, Boolean Inverse = false) { XPathRoot = XPathRoot.ensureStartsWith("/"); List <LeafNodeDictionaryEntry> output = new List <LeafNodeDictionaryEntry>(); List <String> ToRemove = new List <string>(); foreach (var item in items.ToList()) { if (item.XPath.StartsWith(XPathRoot) == !Inverse) { ToRemove.Add(item.XPath); output.Add(item); } } if (DoRemove) { RemoveEntriesByXPath(ToRemove); RebuildIndex(); } return(output); }
/// <summary> /// /// </summary> /// <param name="routeName"></param> /// <param name="writeOnBody"></param> /// <param name="writeMinified"></param> /// <returns></returns> public static HtmlString RequiredScript(String routeName = null, Boolean writeOnBody = false, Boolean writeMinified = true) { var script = ""; script = ScriptProcessorEngine.GetRequiredCode(routeName, writeOnBody, writeMinified); return(new HtmlString(script)); }
public List <LeafNodeDictionaryEntry> GetAndRemoveByTagNames(List <String> tags, Boolean DoRemove = true, Boolean Inverse = false) { List <String> ToRemove = new List <string>(); List <LeafNodeDictionaryEntry> output = new List <LeafNodeDictionaryEntry>(); List <Regex> regexList = new List <Regex>(); //foreach (String tag in tags) //{ // Regex r = new Regex(tag + "\\[[\\d]+\\]\\Z"); // regexList.Add(r); //} foreach (var item in items.ToList()) { String nodeName = XPathTools.GetLastNodeNameFromXPath(item.XPath).ToLower(); if (tags.Contains(nodeName) == !Inverse) { ToRemove.Add(item.XPath); output.Add(item); } //Boolean isMatch = false; //foreach (var r in regexList) //{ // if (r.IsMatch(item.XPath)) // { // isMatch = true; // break; // } //} //if (isMatch == !Inverse) //{ //} } if (DoRemove) { RemoveEntriesByXPath(ToRemove); RebuildIndex(); } return(output); }
void RenderHyperlink(RenderContext context, Boolean inGrid, Action <TagBuilder> onRender = null, Boolean inside = false, Boolean addOn = false) { Boolean bHasDropDown = DropDown != null; var tag = new TagBuilder("a", "a2-hyperlink", inGrid); onRender?.Invoke(tag); var attrMode = MergeAttrMode.All; if (inside) { attrMode &= ~MergeAttrMode.Visibility; } MergeAttributes(tag, context, attrMode); MergeCommandAttribute(tag, context); tag.AddCssClassBool(Block, "block"); tag.AddCssClassBool(Highlight, "highlight"); if (!Block) { tag.AddCssClass("a2-inline"); } if (Size != ControlSize.Default) { switch (Size) { case ControlSize.Small: tag.AddCssClass("small"); break; case ControlSize.Large: tag.AddCssClass("large"); break; case ControlSize.Normal: tag.AddCssClass("normal"); break; default: throw new XamlException("Only ControlSize.Small, ControlSize.Normal or ControlSize.Large is supported for the Hyperlink"); } } if (bHasDropDown) { tag.MergeAttribute("toggle", String.Empty); } tag.RenderStart(context); RenderIcon(context, Icon); var cbind = GetBinding(nameof(Content)); if (cbind != null) { new TagBuilder("span") .MergeAttribute("v-text", cbind.GetPathFormat(context)) .Render(context); } else if (Content is UIElementBase) { (Content as UIElementBase).RenderElement(context); } else if (Content != null) { context.Writer.Write(context.Localize(Content.ToString())); } if (bHasDropDown && !addOn && !HideCaret) { var bDropUp = (DropDown as DropDownMenu)?.IsDropUp; new TagBuilder("span", "caret") .AddCssClassBool(bDropUp, "up") .Render(context); } tag.RenderEnd(context); }
/// <summary> /// Returns a formatted version of the Abstract Syntax Notation One (ASN.1)-encoded alternative name as a string. /// </summary> /// <param name="multiLine"> /// <strong>True</strong> if the return string should contain carriage returns; otherwise, <strong>False</strong>. /// </param> /// <returns>A formatted string that represents the Abstract Syntax Notation One (ASN.1)-encoded alternative name.</returns> public String Format(Boolean multiLine) { String retValue; const String p = " "; String n = Environment.NewLine; switch (Type) { case X509AlternativeNamesEnum.OtherName: retValue = multiLine ? "Other Name:" + n + p + OID.Value + "=" + Value + n : "Other Name:" + OID.Value + "=" + Value + ", "; break; case X509AlternativeNamesEnum.Rfc822Name: retValue = multiLine ? "RFC822 Name=" + Value + n : "RFC822 Name=" + Value + ", "; break; case X509AlternativeNamesEnum.DnsName: retValue = multiLine ? "DNS Name=" + Value + n : "DNS Name=" + Value + ", "; break; case X509AlternativeNamesEnum.DirectoryName: retValue = "Directory Address:"; if (multiLine) { String[] rdns = Value.Split(new []{ ", " }, StringSplitOptions.RemoveEmptyEntries); retValue = rdns.Aggregate(retValue, (current, RDN) => current + p + RDN + n); retValue = retValue.Trim(); } else { retValue = "Directory Address:" + Value + ", "; } break; case X509AlternativeNamesEnum.URL: retValue = multiLine ? "URL=" + Value + n : "URL=" + Value + ", "; break; case X509AlternativeNamesEnum.IpAddress: retValue = multiLine ? "IP Address=" + Value + n : "IP Address=" + Value + ", "; break; case X509AlternativeNamesEnum.RegisteredId: retValue = multiLine ? "Registered ID=" + Value + n : "Registered ID=" + Value + ", "; break; case X509AlternativeNamesEnum.Guid: retValue = multiLine ? "Other Name:" + n + p + OID.FriendlyName + "=" + Value + n : "Other Name:" + OID.FriendlyName + "=" + Value + ", "; break; case X509AlternativeNamesEnum.UserPrincipalName: retValue = multiLine ? "Other Name:" + n + p + OID.FriendlyName + "=" + Value + n : "Other Name:" + OID.FriendlyName + "=" + Value + ", "; break; default: retValue = multiLine ? "Unknown type=" + n + p + Value + n : "Unknown type=" + Value + ", "; break; } retValue = retValue.Trim(); return retValue[retValue.Length - 1] == ',' ? retValue.Substring(0, retValue.Length - 1) : retValue; }
private static void listenToHotKeysAndDoWork() { float rX = 0; float rZ = 0; float rY = 0; // CONTROL PRESSED if (Input.GetKeyDown(KeyCode.LeftControl)) { controlFlag = true; } if (Input.GetKeyUp(KeyCode.LeftControl)) { controlFlag = false; } // SHIFT PRESSED float distance = gDistance; float scrollDistance = gScrollDistance; if (Input.GetKeyDown(KeyCode.LeftShift)) { shiftFlag = true; } if (Input.GetKeyUp(KeyCode.LeftShift)) { shiftFlag = false; } changeModificationSpeeds(shiftFlag); if (shiftFlag) { distance = gDistance * 3; scrollDistance = gScrollDistance * 3; } else { distance = gDistance; scrollDistance = gScrollDistance; } // LEFT ALT PRESSED if (Input.GetKeyDown(KeyCode.LeftAlt)) { altFlag = true; } if (Input.GetKeyUp(KeyCode.LeftAlt)) { altFlag = false; } if (Input.GetAxis("Mouse ScrollWheel") > 0f) { Quaternion rotation; if (controlFlag) { rX++; rotation = Quaternion.Euler(component.transform.eulerAngles.x + (scrollDistance * (float)rX), component.transform.eulerAngles.y, component.transform.eulerAngles.z); // forward to backwards } else { if (altFlag) { rZ++; rotation = Quaternion.Euler(component.transform.eulerAngles.x, component.transform.eulerAngles.y, component.transform.eulerAngles.z + (scrollDistance * (float)rZ)); // diagonal } else { rY++; rotation = Quaternion.Euler(component.transform.eulerAngles.x, component.transform.eulerAngles.y + (scrollDistance * (float)rY), component.transform.eulerAngles.z); // left<->right } } component.transform.rotation = rotation; } if (Input.GetAxis("Mouse ScrollWheel") < 0f) { Quaternion rotation; if (controlFlag) { rX--; rotation = Quaternion.Euler(component.transform.eulerAngles.x + (scrollDistance * (float)rX), component.transform.eulerAngles.y, component.transform.eulerAngles.z); // forward to backwards } else { if (altFlag) { rZ--; rotation = Quaternion.Euler(component.transform.eulerAngles.x, component.transform.eulerAngles.y, component.transform.eulerAngles.z + (scrollDistance * (float)rZ)); // diagonal } else { rY--; rotation = Quaternion.Euler(component.transform.eulerAngles.x, component.transform.eulerAngles.y + (scrollDistance * (float)rY), component.transform.eulerAngles.z); // left<->right } } component.transform.rotation = rotation; } if (Input.GetKeyDown(KeyCode.UpArrow)) { if (controlFlag) { component.transform.Translate(Vector3.up * distance * Time.deltaTime); } else { component.transform.Translate(Vector3.forward * distance * Time.deltaTime); } } if (Input.GetKeyDown(KeyCode.DownArrow)) { if (controlFlag) { component.transform.Translate(Vector3.down * distance * Time.deltaTime); } else { component.transform.Translate(Vector3.back * distance * Time.deltaTime); } } if (Input.GetKeyDown(KeyCode.LeftArrow)) { component.transform.Translate(Vector3.left * distance * Time.deltaTime); } if (Input.GetKeyDown(KeyCode.RightArrow)) { component.transform.Translate(Vector3.right * distance * Time.deltaTime); } try { isValidPlacement(); }catch(Exception e) { } }
/// <summary> /// Constructeur complet de collaborateur avec tous ses paramètres /// </summary> /// <param name="unMatricule">ref au matricule du collaborateur</param> /// <param name="uneCivilite">Civilité du collaborateur</param> /// <param name="situation">Situation maritale du collaborateur</param> /// <param name="unNom">Nom du collaborateur</param> /// <param name="unPrenom">Prénom du collaborateur</param> /// <param name="uneRue">rRue du collaborateur</param> /// <param name="uneVille">Ville du collaborateur</param> /// <param name="unCP">Code postal du collaborateur</param> /// <param name="unTel">Téléphone du collaborateur</param> /// <param name="isArchiv">Etat d'archivage du collaborateur</param> public Collaborateurs(Int32 unMatricule, String uneCivilite, String situation, String unNom, String unPrenom, String uneRue, String uneVille, String unCP, String unTel, Boolean isArchiv) { Archive = isArchiv; matricule = unMatricule; Civilite = uneCivilite; SituationMaritale = situation; Nom = unNom; Prenom = unPrenom; Rue = uneRue; CodePostal = unCP; Ville = uneVille; Telephone = unTel; SortedDictionary <Int32, Contrats> lesContrats = new SortedDictionary <Int32, Contrats>(); }