public static ARC Check(Parse parse, AUTH code, string arg1, string arg2, string arg3) { Context ctx = parse.Ctx; // Don't do any authorization checks if the database is initialising or if the parser is being invoked from within sqlite3_declare_vtab. if (ctx.Init.Busy || E.INDECLARE_VTABLE(parse)) { return(ARC.OK); } if (ctx.Auth == null) { return(ARC.OK); } ARC rc = ctx.Auth(ctx.AuthArg, code, arg1, arg2, arg3, parse.AuthContext); if (rc == ARC.DENY) { parse.ErrorMsg("not authorized"); parse.RC = RC.AUTH; } else if (rc != ARC.OK && rc != ARC.IGNORE) { rc = ARC.DENY; BadReturnCode(parse); } return(rc); }
private void ExtractFileInformation() { int index = 0; using (BinaryReader r = new BinaryReader(new FileStream(ARC.FilePath, FileMode.Open))) { foreach (var file in toExtract) { try { r.BaseStream.Position = (file.ArcOffset); byte[] data = r.ReadBytes((int)file.CompSize); if (file.CompSize != file.DecompSize) { data = ARC.Decompress(data); } string path = "root\\" + file.FilePath.Replace(":", ""); Directory.CreateDirectory(Path.GetDirectoryName(path) + "\\"); File.WriteAllBytes(path, data); index++; Update((int)Math.Floor((index / (float)toExtract.Length) * 100), file.FilePath); } catch (Exception e) { index++; Update(0, e.ToString()); break; } } } }
public int OptimizingLevel = 10; //优化等级,数字越大优化级别越高,越容易失真 public void Set(DXFStructure dxf, ARC item, float ScaleX = 1, float ScaleY = 1) { var goLayer = GoView.Content.GetLayer(item.C8); if (goLayer != null) { lr.material = goLayer.LayerMaterial; ZoomAdjust = goLayer.ZoomAdjust; } float R = (float)item.C40; Diameter = R * 2; float nd = 0;//绘制的角度总数 if (item.C51 > item.C50) { nd = (float)(item.C51 - item.C50); } else { nd = (float)(item.C51 + 360 - item.C50); } //计算一个圆弧需要多少线条 float ndB = nd / 360;//圆弧占用圆的比例 int resolution = (int)(item.C40 / OptimizingLevel * ndB); if (resolution > (int)(MaxResolution * ndB)) { resolution = (int)(MaxResolution * ndB); } if (resolution < (int)(MinResolution * ndB)) { resolution = (int)(MinResolution * ndB); } lr.SetVertexCount(resolution + 1); for (int i = 0; i < resolution; i++) { var ii = (float)(i * nd / (float)resolution); ii += (float)item.C50; if (ii > 360) { ii -= 360; } lr.SetPosition(i, new Vector3((R * Mathf.Cos(2 * Mathf.PI / 360 * ii) + (float)item.C10) * ScaleX, (R * Mathf.Sin(2 * Mathf.PI / 360 * ii) + (float)item.C20) * ScaleY, 0)); } lr.SetPosition(resolution, new Vector3((R * Mathf.Cos(2 * Mathf.PI / 360 * (float)item.C51) + (float)item.C10) * ScaleX, (R * Mathf.Sin(2 * Mathf.PI / 360 * (float)item.C51) + (float)item.C20) * ScaleY, 0)); this.gameObject.isStatic = true; }
public ObservableList <BusinessFlowExecutionSummary> GetAllBusinessFlowsExecutionSummary(bool GetSummaryOnlyForExecutedFlow = false) { ObservableList <BusinessFlowExecutionSummary> BFESs = new ObservableList <BusinessFlowExecutionSummary>(); foreach (GingerRunner ARC in Runners) { BFESs.Append(ARC.GetAllBusinessFlowsExecutionSummary(GetSummaryOnlyForExecutedFlow, ARC.Name)); } return(BFESs); }
static void CodeAttach(Parse parse, AUTH type, FuncDef func, Expr authArg, Expr filename, Expr dbName, Expr key) { Context ctx = parse.Ctx; NameContext sName; sName = new NameContext(); sName.Parse = parse; if (ResolveAttachExpr(sName, filename) != RC.OK || ResolveAttachExpr(sName, dbName) != RC.OK || ResolveAttachExpr(sName, key) != RC.OK) { parse.Errs++; goto attach_end; } #if !OMIT_AUTHORIZATION if (authArg != null) { string authArgToken = (authArg.OP == TK.STRING ? authArg.u.Token : null); ARC arc = Auth.Check(parse, type, authArgToken, null, null); if (arc != ARC.OK) { goto attach_end; } } #endif Vdbe v = parse.GetVdbe(); int regArgs = Expr.GetTempRange(parse, 4); Expr.Code(parse, filename, regArgs); Expr.Code(parse, dbName, regArgs + 1); Expr.Code(parse, key, regArgs + 2); Debug.Assert(v != null || ctx.MallocFailed); if (v != null) { v.AddOp3(OP.Function, 0, regArgs + 3 - func.Args, regArgs + 3); Debug.Assert(func.Args == -1 || (func.Args & 0xff) == func.Args); v.ChangeP5((byte)(func.Args)); v.ChangeP4(-1, func, Vdbe.P4T.FUNCDEF); // Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this statement only). For DETACH, set it to false (expire all existing statements). v.AddOp1(OP.Expire, (type == AUTH.ATTACH ? 1 : 0)); } attach_end: Expr.Delete(ctx, ref filename); Expr.Delete(ctx, ref dbName); Expr.Delete(ctx, ref key); }
void Start() { screenRect = new Rect(0, 0, Screen.width, Screen.height); camTexture = new WebCamTexture(); camTexture.requestedHeight = Screen.height; camTexture.requestedWidth = Screen.width; MC = GameObject.Find("Main Camera"); MC.GetComponent <UnityARVideo>().enabled = false; ARC = GameObject.Find("ARCameraManager"); ARC.GetComponent <UnityARCameraManager> ().enabled = false; if (camTexture != null) { camTexture.Play(); } }
protected void LoadCategories() { ARC arc = ArcBAL.GetArcInfoByUserId(new Guid(Session[enumSessions.User_Id.ToString()].ToString())); if (arc == null) { string script = "alertify.alert('" + ltrUser.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); return; } List <CategoryDTO> categories = CategoryBAL.GetCategoriesByArcId(arc.ARCId); dtCategories.DataSource = categories; dtCategories.DataBind(); }
public MainForm() { InitializeComponent(); ArcFile = new ARC(); treeView1.BeforeExpand += folderTree_BeforeExpand; treeView1.NodeMouseClick += (sender, args) => treeView1.SelectedNode = args.Node; treeView1.HideSelection = false; treeView1.ImageList = new ImageList(); treeView1.ImageList.Images.Add("folder", Properties.Resources.folder); treeView1.ImageList.Images.Add("file", Properties.Resources.file); comboBox1.SelectedIndex = SelectedRegion; comboBox1.SelectedIndexChanged += (sender, args) => { SelectedRegion = comboBox1.SelectedIndex; treeView1_AfterSelect(null, null); }; NodeContextMenu = new ContextMenu(); { MenuItem item = new MenuItem("Extract file(s)"); item.Click += ExtractFile; NodeContextMenu.MenuItems.Add(item); } { MenuItem item = new MenuItem("Extract file(s) (Compressed)"); item.Click += ExtractFileComp; NodeContextMenu.MenuItems.Add(item); } { MenuItem item = new MenuItem("Extract file(s) (With Offset)"); item.Click += ExtractFileOffset; NodeContextMenu.MenuItems.Add(item); } { MenuItem item = new MenuItem("Extract file(s) (Compressed, With Offset)"); item.Click += ExtractFileCompOffset; NodeContextMenu.MenuItems.Add(item); } }
public static ARC GetArcInfoByUserId(Guid userID) { ARC arcDetails = new ARC(); LinqToSqlDataContext db = new LinqToSqlDataContext(); arcDetails = (from arc in db.ARCs join aup in db.ARC_User_Maps on arc.ARCId equals aup.ARCId where ( (arc.IsDeleted == false) && (aup.UserId == userID) ) select arc).FirstOrDefault(); db.Dispose(); return(arcDetails); }
private void ProcessStrings() { list_Search.Items.Clear(); var files = Directory.GetFiles(s06PathBox.Text, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".arc")); foreach (string selectedARC in clb_ARCs.CheckedItems) { foreach (var ARC in files) { if (ARC.Contains(selectedARC)) { using (FileStream stream = new FileStream(ARC, FileMode.Open)) { // here is some stream 'stream' which contains any number of bytes, where we search for various strings inside of it FindStrings(stream, new string[] { searchBox.Text }, Path.GetFileName(ARC)); } } } } }
public static ARC CreateARC(ARC arc) { using (LinqToSqlDataContext db = new LinqToSqlDataContext()) { if (string.IsNullOrEmpty(arc.UNiqueCode)) { ISingleResult <SP_GenerateAccountUniqueCodeResult> result = db.SP_GenerateAccountUniqueCode(arc.CompanyName, arc.ArcTypeId.HasValue ? arc.ArcTypeId : 1, arc.CreatedBy); if (result == null) { throw new Exception("Unable to Generate a Unique Code using the SP: SP_GenerateAccountUniqueCode"); } else { arc.UNiqueCode = result.FirstOrDefault().Column1.Value.ToString(); } } db.ARCs.InsertOnSubmit(arc); db.SubmitChanges(); } return(arc); //returns the same object with ARCId filled in }
void OnGUI() { if (url != "") { return; } // drawing the camera on screen GUI.DrawTexture(screenRect, camTexture, ScaleMode.ScaleToFit); // do the reading — you might want to attempt to read less often than you draw on the screen for performance sake try { IBarcodeReader barcodeReader = new BarcodeReader(); // decode the current frame var result = barcodeReader.Decode(camTexture.GetPixels32(), camTexture.width, camTexture.height); if (result != null) { Debug.Log("DECODED TEXT FROM QR: " + result.Text); url = result.Text; camTexture.Stop(); MC.GetComponent <UnityARVideo>().enabled = true; ARC.GetComponent <UnityARCameraManager> ().enabled = true; } } catch (System.Exception ex) { Debug.LogWarning(ex.Message); } }
public static ARC ReadColumn(Parse parse, string table, string column, int db) { Context ctx = parse.Ctx; // Database handle string dbName = ctx.DBs[db].Name; // Name of attached database ARC rc = ctx.Auth(ctx.AuthArg, (int)AUTH.READ, table, column, dbName, parse.AuthContext); // Auth callback return code if (rc == ARC.DENY) { if (ctx.DBs.length > 2 || db != 0) { parse.ErrorMsg("access to %s.%s.%s is prohibited", dbName, table, column); } else { parse.ErrorMsg("access to %s.%s is prohibited", table, column); } parse.RC = RC.AUTH; } else if (rc != ARC.IGNORE && rc != ARC.OK) { BadReturnCode(parse); } return(rc); }
public void FKCheck(Table table, int regOld, int regNew) { Context ctx = Ctx; // Database handle bool isIgnoreErrors = DisableTriggers; // Exactly one of regOld and regNew should be non-zero. Debug.Assert((regOld == 0) != (regNew == 0)); // If foreign-keys are disabled, this function is a no-op. if ((ctx.Flags & Context.FLAG.ForeignKeys) == 0) { return; } int db = SchemaToIndex(ctx, table.Schema); // Index of database containing pTab string dbName = ctx.DBs[db].Name; // Name of database containing pTab // Loop through all the foreign key constraints for which pTab is the child table (the table that the foreign key definition is part of). FKey fkey; // Used to iterate through FKs for (fkey = table.FKeys; fkey != null; fkey = fkey.NextFrom) { bool isIgnore = false; // Find the parent table of this foreign key. Also find a unique index on the parent key columns in the parent table. If either of these // schema items cannot be located, set an error in pParse and return early. Table to = (DisableTriggers ? FindTable(ctx, fkey.To, dbName) : LocateTable(false, fkey.To, dbName)); // Parent table of foreign key pFKey Index index = null; // Index on key columns in pTo int[] frees = null; if (to == null || LocateFkeyIndex(to, fkey, out index, out frees) != 0) { Debug.Assert(!isIgnoreErrors || (regOld != 0 && regNew == 0)); if (!isIgnoreErrors || ctx.MallocFailed) { return; } if (to == null) { // If isIgnoreErrors is true, then a table is being dropped. In this se SQLite runs a "DELETE FROM xxx" on the table being dropped // before actually dropping it in order to check FK constraints. If the parent table of an FK constraint on the current table is // missing, behave as if it is empty. i.e. decrement the FK counter for each row of the current table with non-NULL keys. Vdbe v = GetVdbe(); int jumpId = v.CurrentAddr() + fkey.Cols.length + 1; for (int i = 0; i < fkey.Cols.length; i++) { int regId = fkey.Cols[i].From + regOld + 1; v.AddOp2(OP.IsNull, regId, jumpId); } v.AddOp2(OP.FkCounter, fkey.IsDeferred, -1); } continue; } Debug.Assert(fkey.Cols.length == 1 || (frees != null && index != null)); int[] cols; if (frees != null) { cols = frees; } else { int col = fkey.Cols[0].From; cols = new int[1]; cols[0] = col; } for (int i = 0; i < fkey.Cols.length; i++) { if (cols[i] == table.PKey) { cols[i] = -1; } #if !OMIT_AUTHORIZATION // Request permission to read the parent key columns. If the authorization callback returns SQLITE_IGNORE, behave as if any // values read from the parent table are NULL. if (ctx.Auth != null) { string colName = to.Cols[index != null ? index.Columns[i] : to.PKey].Name; ARC rcauth = Auth.ReadColumn(this, to.Name, colName, db); isIgnore = (rcauth == ARC.IGNORE); } #endif } // Take a shared-cache advisory read-lock on the parent table. Allocate a cursor to use to search the unique index on the parent key columns // in the parent table. TableLock(db, to.Id, false, to.Name); Tabs++; if (regOld != 0) // A row is being removed from the child table. Search for the parent. If the parent does not exist, removing the child row resolves an outstanding foreign key constraint violation. { FKLookupParent(this, db, to, index, fkey, cols, regOld, -1, isIgnore); } if (regNew != 0) // A row is being added to the child table. If a parent row cannot be found, adding the child row has violated the FK constraint. { FKLookupParent(this, db, to, index, fkey, cols, regNew, +1, isIgnore); } C._tagfree(ctx, ref frees); } // Loop through all the foreign key constraints that refer to this table for (fkey = FKReferences(table); fkey != null; fkey = fkey.NextTo) { if (!fkey.IsDeferred && Toplevel == null && !IsMultiWrite) { Debug.Assert(regOld == 0 && regNew != 0); // Inserting a single row into a parent table cannot cause an immediate foreign key violation. So do nothing in this case. continue; } Index index = null; // Foreign key index for pFKey int[] cols = null; if (LocateFkeyIndex(table, fkey, out index, out cols) != 0) { if (isIgnoreErrors || ctx.MallocFailed) { return; } continue; } Debug.Assert(cols != null || fkey.Cols.length == 1); // Create a SrcList structure containing a single table (the table the foreign key that refers to this table is attached to). This // is required for the sqlite3WhereXXX() interface. SrcList src = SrcListAppend(ctx, null, null, null); if (src != null) { SrcList.SrcListItem item = src.Ids[0]; item.Table = fkey.From; item.Name = fkey.From.Name; item.Table.Refs++; item.Cursor = Tabs++; if (regNew != 0) { FKScanChildren(this, src, table, index, fkey, cols, regNew, -1); } if (regOld != 0) { // If there is a RESTRICT action configured for the current operation on the parent table of this FK, then throw an exception // immediately if the FK constraint is violated, even if this is a deferred trigger. That's what RESTRICT means. To defer checking // the constraint, the FK should specify NO ACTION (represented using OE_None). NO ACTION is the default. FKScanChildren(this, src, table, index, fkey, cols, regOld, 1); } item.Name = null; SrcListDelete(ctx, ref src); } C._tagfree(ctx, ref cols); } }
// Use this for initialization void Start() { cName.text = character._characterName; race.text = character._characterRace.ToString(); HP.text = "" + character.GetCurrentHealth() + " / " + character.GetMaxHealth(); STR = character.GetAbilityScore(AbilityID.Strength); DEX = character.GetAbilityScore(AbilityID.Dexterity); CON = character.GetAbilityScore(AbilityID.Constitution); INT = character.GetAbilityScore(AbilityID.Intelligence); WIS = character.GetAbilityScore(AbilityID.Wisdom); CHA = character.GetAbilityScore(AbilityID.Charisma); ATH = character.GetSkill(SkillID.Athletics); ACR = character.GetSkill(SkillID.Acrobatics); STE = character.GetSkill(SkillID.Stealth); THI = character.GetSkill(SkillID.Thievery); END = character.GetSkill(SkillID.Endurance); ARC = character.GetSkill(SkillID.Arcana); HIS = character.GetSkill(SkillID.History); REL = character.GetSkill(SkillID.Religion); DUN = character.GetSkill(SkillID.Dungeoneering); HEA = character.GetSkill(SkillID.Heal); INS = character.GetSkill(SkillID.Insight); NAT = character.GetSkill(SkillID.Nature); PER = character.GetSkill(SkillID.Perception); BLU = character.GetSkill(SkillID.Bluff); DIP = character.GetSkill(SkillID.Diplomacy); INTI = character.GetSkill(SkillID.Intimidate); STRE = character.GetSkill(SkillID.Streetwise); tSTR.text = STR + " +" + character.GetModifier(AbilityID.Strength); tDEX.text = DEX + " +" + character.GetModifier(AbilityID.Dexterity); tCON.text = CON + " +" + character.GetModifier(AbilityID.Constitution); tINT.text = INT + " +" + character.GetModifier(AbilityID.Intelligence); tWIS.text = WIS + " +" + character.GetModifier(AbilityID.Wisdom); tCHA.text = CHA + " +" + character.GetModifier(AbilityID.Charisma); tAC.text = character.GetDefence(DefenceID.ArmorClass).ToString(); tFO.text = character.GetDefence(DefenceID.Fortitude).ToString(); tRE.text = character.GetDefence(DefenceID.Reflex).ToString(); tWI.text = character.GetDefence(DefenceID.Will).ToString(); tATH.text = ATH.ToString(); tACR.text = ACR.ToString(); tSTE.text = STE.ToString(); tTHI.text = THI.ToString(); tEND.text = END.ToString(); tARC.text = ARC.ToString(); tHIS.text = HIS.ToString(); tREL.text = REL.ToString(); tDUN.text = DUN.ToString(); tHEA.text = HEA.ToString(); tINS.text = INS.ToString(); tNAT.text = NAT.ToString(); tPER.text = PER.ToString(); tBLU.text = BLU.ToString(); tDIP.text = DIP.ToString(); tINTI.text = INTI.ToString(); tSTRE.text = STRE.ToString(); }
static WRC ResolveExprStep(Walker walker, Expr expr) { NameContext nc = walker.u.NC; Debug.Assert(nc != null); Parse parse = nc.Parse; Debug.Assert(parse == walker.Parse); if (E.ExprHasAnyProperty(expr, EP.Resolved)) { return(WRC.Prune); } E.ExprSetProperty(expr, EP.Resolved); #if !NDEBUG if (nc.SrcList != null && nc.SrcList.Allocs > 0) { SrcList srcList = nc.SrcList; for (int i = 0; i < nc.SrcList.Srcs; i++) { Debug.Assert(srcList.Ids[i].Cursor >= 0 && srcList.Ids[i].Cursor < parse.Tabs); } } #endif switch (expr.OP) { #if ENABLE_UPDATE_DELETE_LIMIT && !OMIT_SUBQUERY // The special operator TK_ROW means use the rowid for the first column in the FROM clause. This is used by the LIMIT and ORDER BY // clause processing on UPDATE and DELETE statements. case TK.ROW: { SrcList srcList = nc.SrcList; Debug.Assert(srcList != null && srcList.Srcs == 1); SrcList.SrcListItem item = srcList.Ids[0]; expr.OP = TK.COLUMN; expr.Table = item.Table; expr.TableId = item.Cursor; expr.ColumnIdx = -1; expr.Aff = AFF.INTEGER; break; } #endif case TK.ID: // A lone identifier is the name of a column. { return(LookupName(parse, null, null, expr.u.Token, nc, expr)); } case TK.DOT: // A table name and column name: ID.ID Or a database, table and column: ID.ID.ID { string columnName; string tableName; string dbName; // if (srcList == nullptr) break; Expr right = expr.Right; if (right.OP == TK.ID) { dbName = null; tableName = expr.Left.u.Token; columnName = right.u.Token; } else { Debug.Assert(right.OP == TK.DOT); dbName = expr.Left.u.Token; tableName = right.Left.u.Token; columnName = right.Right.u.Token; } return(LookupName(parse, dbName, tableName, columnName, nc, expr)); } case TK.CONST_FUNC: case TK.FUNCTION: // Resolve function names { ExprList list = expr.x.List; // The argument list int n = (list != null ? list.Exprs : 0); // Number of arguments bool noSuchFunc = false; // True if no such function exists bool wrongNumArgs = false; // True if wrong number of arguments bool isAgg = false; // True if is an aggregate function TEXTENCODE encode = E.CTXENCODE(parse.Ctx); // The database encoding C.ASSERTCOVERAGE(expr.OP == TK.CONST_FUNC); Debug.Assert(!E.ExprHasProperty(expr, EP.xIsSelect)); string id = expr.u.Token; // The function name. int idLength = id.Length; // Number of characters in function name FuncDef def = Callback.FindFunction(parse.Ctx, id, idLength, n, encode, false); // Information about the function if (def == null) { def = Callback.FindFunction(parse.Ctx, id, idLength, -2, encode, false); if (def == null) { noSuchFunc = true; } else { wrongNumArgs = true; } } else { isAgg = (def.Func == null); } #if !OMIT_AUTHORIZATION if (def != null) { ARC auth = Auth.Check(parse, AUTH.FUNCTION, null, def.Name, null); // Authorization to use the function if (auth != ARC.OK) { if (auth == ARC.DENY) { parse.ErrorMsg("not authorized to use function: %s", def.Name); nc.Errs++; } expr.OP = TK.NULL; return(WRC.Prune); } } #endif if (isAgg && (nc.NCFlags & NC.AllowAgg) == 0) { parse.ErrorMsg("misuse of aggregate function %.*s()", idLength, id); nc.Errs++; isAgg = false; } else if (noSuchFunc && !ctx.Init.Busy) { parse.ErrorMsg("no such function: %.*s", idLength, id); nc.Errs++; } else if (wrongNumArgs) { parse.ErrorMsg("wrong number of arguments to function %.*s()", idLength, id); nc.Errs++; } if (isAgg) { nc.NCFlags &= ~NC.AllowAgg; } walker.WalkExprList(list); if (isAgg) { NameContext nc2 = nc; expr.OP = TK.AGG_FUNCTION; expr.OP2 = 0; while (nc2 != null && !expr.FunctionUsesThisSrc(nc2.SrcList)) { expr.OP2++; nc2 = nc2.Next; } if (nc2 != null) { nc2.NCFlags |= NC.HasAgg; } nc.NCFlags |= NC.AllowAgg; } // FIX ME: Compute pExpr->affinity based on the expected return type of the function return(WRC.Prune); } #if !OMIT_SUBQUERY case TK.SELECT: case TK.EXISTS: { C.ASSERTCOVERAGE(expr.OP == TK.EXISTS); goto case TK.IN; } #endif case TK.IN: { C.ASSERTCOVERAGE(expr.OP == TK.IN); if (E.ExprHasProperty(expr, EP.xIsSelect)) { int refs = nc.Refs; #if !OMIT_CHECK if ((nc.NCFlags & NC.IsCheck) != 0) { parse.ErrorMsg("subqueries prohibited in CHECK constraints"); } #endif walker.WalkSelect(expr.x.Select); Debug.Assert(nc.Refs >= refs); if (refs != nc.Refs) { E.ExprSetProperty(expr, EP.VarSelect); } } break; } #if !OMIT_CHECK case TK.VARIABLE: { if ((nc.NCFlags & NC.IsCheck) != 0) { parse.ErrorMsg("parameters prohibited in CHECK constraints"); } break; } #endif } return(parse.Errs != 0 || parse.Ctx.MallocFailed ? WRC.Abort : WRC.Continue); }
public void LoadUserInfo() { if (Session[enumSessions.User_Id.ToString()] != null) { ARC arc = ArcBAL.GetArcInfoByUserId(new Guid(Session[enumSessions.User_Id.ToString()].ToString())); if (arc == null) { ltrErrorMsg.Text = "User does not belong to any ARC."; return; } if (arc.IsBulkUploadAllowed) { hyprLnkBulkUpload.Visible = true; } Session[enumSessions.ARC_Id.ToString()] = arc.ARCId; Session[enumSessions.IsARC_AllowReturns.ToString()] = arc.AllowReturns; lblUsername.Text = Session[enumSessions.User_Name.ToString()].ToString(); if (arc.CompanyName.Length > 30) { lblARCCompany.Text = arc.CompanyName.Substring(0, 30) + "..."; } else { lblARCCompany.Text = arc.CompanyName; } LinqToSqlDataContext db = new LinqToSqlDataContext(); var OrderInfo = db.USP_CreateOrderForUser(arc.ARCId, Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Email.ToString()].ToString(), Session[enumSessions.User_Id.ToString()].ToString()).SingleOrDefault(); if (OrderInfo != null) { Session[enumSessions.OrderId.ToString()] = OrderInfo.OrderId; lblOrderTotal.Text = OrderInfo.Amount.ToString(); Session[enumSessions.HasUserAcceptedDuplicates.ToString()] = OrderInfo.HasUserAcceptedDuplicates; lblBasket.Text = OrderInfo.Quantity.ToString(); Session[enumSessions.OrderNumber.ToString()] = OrderInfo.OrderNo.ToString(); basketProducts = db.OrderItems.Where(num => num.OrderId == Convert.ToInt32(Session[enumSessions.OrderId.ToString()])).Count().ToString(); if (basketProducts == "0") { basketProducts = string.Empty; } if (OrderInfo.InstallerId != "0") { Session[enumSessions.InstallerCompanyID.ToString()] = OrderInfo.InstallerId; Session[enumSessions.SelectedInstaller.ToString()] = OrderInfo.SelectedInstaller; } } db.Dispose(); if (Session[enumSessions.User_Role.ToString()] != null && Session[enumSessions.User_Role.ToString()].ToString() == enumRoles.ARC_Admin.ToString()) { lblOrderTotal.Text = "0.00"; // AarcadminMenu.Style.Add("visibility", "visible"); } Amyacc.Style.Add("visibility", "visible"); // Visible for all if (Session[enumSessions.SelectedInstaller.ToString()] != null) { if (Session[enumSessions.SelectedInstaller.ToString()].ToString().Length > 30) { lblInstallerName.Text = Session[enumSessions.SelectedInstaller.ToString()].ToString().Substring(0, 30) + "..."; } else { lblInstallerName.Text = Session[enumSessions.SelectedInstaller.ToString()].ToString(); } } if (Session[enumSessions.InstallerCompanyID.ToString()] != null) { HyperLink1.Enabled = true; } btnLogOut.Visible = true; } else { lblUsername.Text = "Guest"; lblARCCompany.Text = "Guest"; lblBasket.Text = "0"; lblOrderTotal.Text = "0.00"; lblInstallerName.Text = ""; } }
public static void SendEmailWithPrice(string OrderNo, string mailTO, SendEmailDTO sendEmailDTO, string mailFrom, string mailCC, bool isEmailFromViewOrders, bool?hasEmizonProducts, int orderID) { try { String ProductsList = ""; bool instadd_differs = false; string subjectsuffix = string.Empty; string templatePath = "Template"; SendEmailMessage sendEmail = new SendEmailMessage(); EmailMessage cslEmailMessage = new EmailMessage(); string emizonQueuePath = ConfigurationManager.AppSettings["EmizonQueue"].ToString();//could have used AppSettings but no point as another one is using config string mailSubject = "Order Confirmation - Order Ref: " + OrderNo; if (isEmailFromViewOrders) { if (mailTO.EndsWith("@csldual.com")) { subjectsuffix = "; Email Resent"; } mailSubject = mailSubject + subjectsuffix; templatePath = "../Template"; } String mailHtml = ReadTemplates.ReadMailTemplate(System.Web.HttpContext.Current.Server.MapPath(templatePath), "EmailTemplate.html"); StringBuilder objBuilder = new StringBuilder(); objBuilder.Append(mailHtml); objBuilder.Replace("{OrderNo}", OrderNo); objBuilder.Replace("{OrderDate}", string.IsNullOrEmpty(sendEmailDTO.orderDate) ? "." : sendEmailDTO.orderDate); objBuilder.Replace("{OrderRef}", string.IsNullOrEmpty(sendEmailDTO.ARCOrderRefNo) ? "." : sendEmailDTO.ARCOrderRefNo); ARC arc = ArcBAL.GetArcInfoByUserId(new Guid(sendEmailDTO.userID)); string arcAdd = ""; if (arc != null) { arcAdd = arc.CompanyName == null ? "" : arc.CompanyName + ", "; arcAdd += arc.AddressOne + ", <br /> "; arcAdd += string.IsNullOrEmpty(arc.AddressTwo) ? "" : arc.AddressTwo + ", "; arcAdd += string.IsNullOrEmpty(arc.Town) ? "" : arc.Town + ",<br /> "; arcAdd += string.IsNullOrEmpty(arc.County) ? "" : arc.County + ", "; arcAdd += string.IsNullOrEmpty(arc.PostCode) ? "" : arc.PostCode + " <br />"; objBuilder.Replace("{Fax}", string.IsNullOrEmpty(arc.Fax) ? "." : arc.Fax); objBuilder.Replace("{Tel}", string.IsNullOrEmpty(arc.Telephone) ? "." : arc.Telephone); objBuilder.Replace("{ARC}", arcAdd); } objBuilder.Replace("{Username}", sendEmailDTO.userName); objBuilder.Replace("{UserEmail}", sendEmailDTO.userEmail); // OrderDetails LinqToSqlDataContext db = new LinqToSqlDataContext(); var products = db.USP_GetBasketProducts(Convert.ToInt32(sendEmailDTO.orderID)).ToList(); if (products != null && products.Count > 0) { string chipNos = ""; int countOption = 1; foreach (var prod in products) { int rowCount = db.USP_GetBasketProductsOnCheckOut(Convert.ToInt32(sendEmailDTO.orderID)).Where(i => i.ProductCode == prod.ProductCode.Trim()).Count(); ProductsList += "<tr><td style=\"background: #FFF7F7\">" + prod.ProductCode + "</td><td>" + prod.ProductName + "</td> <td style=\"background: #FFF7F7\">" + prod.ProductQty + "</td><td>£" + prod.Price; if (prod.ProductType == "Product") { chipNos = ""; var ChipNumbers = db.USP_GetBasketGPRSChipNumbersByProductId(Convert.ToInt32(sendEmailDTO.orderID), prod.ProductId, prod.CategoryId).ToList(); if (ChipNumbers != null) { foreach (var chipno in ChipNumbers) { chipNos += string.IsNullOrEmpty(chipno.GPRSNo) ? "" : chipno.GPRSNo + "-"; chipNos += string.IsNullOrEmpty(chipno.PSTNNo) ? "" : chipno.PSTNNo + "-"; chipNos += string.IsNullOrEmpty(chipno.GSMNo) ? "" : chipno.GSMNo + "-"; //added GSM NO(PanelID) in email chipNos += string.IsNullOrEmpty(chipno.OptionName) ? "" : chipno.OptionName; chipNos += ","; if (chipno.PSTNNo == "" && chipno.OptionName == "" && chipno.GSMNo == "" && chipNos.Length > 0 )//added GSM NO(PanelID) in email { chipNos = chipNos.Remove(chipNos.Length - 1, 1); } } if (chipNos != "") { chipNos = chipNos.Substring(0, chipNos.Length - 1); ProductsList += "</td> <td style=\"background: #FFF7F7\">" + chipNos + "</td> </td></tr>"; } else { ProductsList += "</td> <td style=\"background: #FFF7F7\">Chip Numbers : Not Provided</td></tr>"; } } if (rowCount == 1) { var dependentproducts = db.USP_GetBasketDependentProductsByProductId(Convert.ToInt32(sendEmailDTO.orderID), prod.ProductId, prod.CategoryId).ToList(); if (dependentproducts != null && dependentproducts.Count > 0) { foreach (var dp in dependentproducts) { ProductsList += "<tr><td>" + dp.ProductCode + "</td><td>" + dp.ProductName + "</td><td>" + dp.ProductQty + "</td><td>£" + dp.Price + "</tr>"; } } countOption = 0; } else if (rowCount == countOption) { var dependentproducts = db.USP_GetBasketDependentProductsByProductId(Convert.ToInt32(sendEmailDTO.orderID), prod.ProductId, prod.CategoryId).ToList(); if (dependentproducts != null && dependentproducts.Count > 0) { foreach (var dp in dependentproducts) { ProductsList += "<tr><td>" + dp.ProductCode + "</td><td>" + dp.ProductName + "</td><td>" + dp.ProductQty + "</td><td>£" + dp.Price + "</tr>"; } } } } countOption++; } } OrderDTO objorder = CSLOrderingARCBAL.BAL.OrdersBAL.GetOrderDetail(Convert.ToInt32(sendEmailDTO.orderID)); //objBuilder.Replace("{OrderTotal}", Convert.ToDecimal(lblDtlsOrderTotal.Text).ToString("c")); objBuilder.Replace("{OrderTotal}", "£" + Convert.ToDecimal(objorder.OrderTotal)); //objBuilder.Replace("{DeliveryTotal}", Convert.ToDecimal(lblDtlsDeliveryTotal.Text).ToString("c")); objBuilder.Replace("{DeliveryTotal}", "£" + Convert.ToDecimal(objorder.DeliveryCost)); //objBuilder.Replace("{VAT}", Convert.ToDecimal(lblDtlsVAT.Text).ToString("c")); objBuilder.Replace("{VAT}", "£" + Convert.ToDecimal(objorder.VATAmount)); //objBuilder.Replace("{TotalToPay}", Convert.ToDecimal(lblDtlsTotalToPay.Text).ToString("c")); objBuilder.Replace("{TotalToPay}", "£" + Convert.ToDecimal(objorder.TotalAmountToPay)); objBuilder.Replace("{DeliveryTypeName}", string.IsNullOrEmpty(sendEmailDTO.DdeliveryType) ? "" : sendEmailDTO.DdeliveryType); objBuilder.Replace("{DeliveryTypePrice}", "£" + sendEmailDTO.deliveryCost); objBuilder.Replace("{Installer}", InstallerBAL.GetAddressHTML2LineForEmail(new Guid(sendEmailDTO.installerID))); if (objorder.InstallationAddressId > 0) { instadd_differs = true; } else { instadd_differs = false; } if (instadd_differs)// || sendEmailDTO.InstallationAddId != 0) { //string InsAdd = InstallerBAL.GetAddressHTML2LineForEmail(Convert.ToInt32(Session[enumSessions.PreviousOrderId.ToString()].ToString())); string InsAdd = objorder.InstallationAddressId.HasValue ? InstallerBAL.GetAddressHTML2LineForEmail(objorder.InstallationAddressId.Value) : "Not Available"; objBuilder.Replace("{InstallerAddress}", "<td><div style=\"width: 100%; margin: 0; padding: 0;\"><table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\"><tr><td style=\"text-align: left\"> <font color=\"#888\" size=\"2\" face=\"Arial\">" + InsAdd + " </font></td></tr></table></div></td>"); objBuilder.Replace("{HeadingInstallerAdd}", "<td><h3 style=\"font-size:11px; text-align: center; margin: 0; padding: 5px auto;\">Installation Address</h3></td>"); } else { objBuilder.Replace("{InstallerAddress}", ""); objBuilder.Replace("{HeadingInstallerAdd}", ""); } objBuilder.Replace("{DeliveredTo}", OrdersBAL.GetDeliveryAddressHTML2Line(Convert.ToInt32(sendEmailDTO.orderID))); objBuilder.Replace("{SpecialInstructions}", sendEmailDTO.specialInstructions); if (isEmailFromViewOrders) { objBuilder.Append("Email Resent"); } var distinctProduct = products.Select(i => i.ProductCode).Distinct(); foreach (var pro in distinctProduct) { products = db.USP_GetBasketProducts(Convert.ToInt32(sendEmailDTO.orderID)).Where(p => p.ProductCode == pro).Take(1).ToList(); foreach (var prod in products) { if (prod.IsCSDUser == true) { ProductsList += "<tr><td>" + prod.ProductCode + "</td><td>" + prod.Message + "</td></tr>"; } } } objBuilder.Replace("{ProductList}", ProductsList); if (mailTO != "" && mailTO.Trim() != "") { string[] mailFromList = mailFrom.Split(','); string[] mailCCList = mailCC.Split(','); string emailCC = string.Empty; foreach (string email in mailCCList) { emailCC += email + ","; } if (!string.IsNullOrEmpty(emailCC)) { emailCC = emailCC.TrimEnd(','); } //PUSH TO EMIZON QUEUE if (hasEmizonProducts.HasValue && hasEmizonProducts.Value) { EmizonOrderController.AddAPIRequestToQueue(emizonQueuePath, new Emizon.APIModels.MSMQTypes.QueueOrderMessage() { From = mailFrom, To = mailTO, CC = mailCC, BCC = mailCC, Subject = mailSubject, OrderHTMLBody = objBuilder.ToString(), orderID = orderID }); } else { //Add below code to send the email message via msmq not smtp -Priya 15/06/2017 //Remove Emizon placeholder objBuilder.Replace("{EmizonData}", ""); cslEmailMessage.From = mailFrom; cslEmailMessage.To = mailTO; cslEmailMessage.CC = emailCC; cslEmailMessage.BCC = emailCC; cslEmailMessage.Subject = mailSubject; cslEmailMessage.Message = objBuilder.ToString(); sendEmail.SendEmailMessageToQueue(ConfigurationManager.AppSettings["QueueName"].ToString(), cslEmailMessage); } //End Code sending email to msmq. } ApplicationDTO appSettings = new AppSettings().GetAppValues(); List <string> lstProductCodes = new List <string>(); lstProductCodes = appSettings.ConnectionOnlyCodes.Split(',').ToList(); bool connectionProductCodeExist = false; foreach (var x in distinctProduct) { if (lstProductCodes.Exists(e => e.EndsWith(x))) { connectionProductCodeExist = true; } } StringBuilder strURL = new StringBuilder(); if (connectionProductCodeExist) { #region buildURLs List <DCCCompany> lstDCCCompany = db.DCCCompanies.ToList(); foreach (DCCCompany company in lstDCCCompany) { var tableCodes = company.Productcode.Split(',').ToList(); foreach (string s in tableCodes) { if (distinctProduct.Contains(s)) //only create a link if the product exist in the basket items. { strURL.Append(" please <a href='" + company.InstructionsUrl + "'>Click here for " + company.company_name + "</a> or "); break; // once we add } } } #endregion string mailSubjectConnectionOnly = "ARC Connection Only - Order Confirmation - Order Ref: " + OrderNo; if (isEmailFromViewOrders) { if (mailTO.EndsWith("@csldual.com")) { subjectsuffix = "; Email Resent"; } mailSubjectConnectionOnly = mailSubjectConnectionOnly + subjectsuffix; } String mailHtmlConnectionOnly = ReadTemplates.ReadMailTemplate(System.Web.HttpContext.Current.Server.MapPath(templatePath), "EmailTemplate_ConnectionOrders.html"); // String mailHtmlConnectionOnly = ReadTemplates.ReadMailTemplate(System.Web.HttpContext.Current.Server.MapPath(templatePath), "EmailTemplate_v2_ConnectionOrders.html"); StringBuilder objBuilderConnectionOnly = new StringBuilder(); objBuilderConnectionOnly.Append(mailHtmlConnectionOnly); objBuilderConnectionOnly.Replace("{InstallationURL}", strURL.ToString().TrimEnd(' ', 'o', 'r') + '.'); objBuilderConnectionOnly.Replace("{OrderNo}", OrderNo); objBuilderConnectionOnly.Replace("{OrderDate}", sendEmailDTO.orderDate); objBuilderConnectionOnly.Replace("{OrderRef}", string.IsNullOrEmpty(sendEmailDTO.ARCOrderRefNo) ? "." : sendEmailDTO.ARCOrderRefNo); objBuilderConnectionOnly.Replace("{OrderTotal}", "£" + objorder.OrderTotal); objBuilderConnectionOnly.Replace("{DeliveryTotal}", "£" + objorder.DeliveryCost); objBuilderConnectionOnly.Replace("{VAT}", "£" + objorder.VATAmount); objBuilderConnectionOnly.Replace("{TotalToPay}", "£" + objorder.TotalAmountToPay); objBuilderConnectionOnly.Replace("{DeliveryTypeName}", sendEmailDTO.DdeliveryType.ToString().TrimEnd(' ')); // objBuilderConnectionOnly.Replace("{DeliveryTypePrice}", "£" + sendEmailDTO.deliveryCost); objBuilderConnectionOnly.Replace("{Installer}", InstallerBAL.GetAddressHTML2LineForEmail(new Guid(sendEmailDTO.installerID))); if (arc != null) { objBuilderConnectionOnly.Replace("{Fax}", string.IsNullOrEmpty(arc.Fax) ? "." : arc.Fax); objBuilderConnectionOnly.Replace("{Tel}", string.IsNullOrEmpty(arc.Telephone) ? "." : arc.Telephone); objBuilderConnectionOnly.Replace("{ARC}", arcAdd); } objBuilderConnectionOnly.Replace("{Username}", sendEmailDTO.userName); objBuilderConnectionOnly.Replace("{UserEmail}", sendEmailDTO.userEmail); //comment below line if new RAc connection only template is approved if (instadd_differs) { string InsAddConnection = objorder.InstallationAddressId.HasValue ? InstallerBAL.GetAddressHTML2LineForEmail(objorder.InstallationAddressId.Value) : "Not Available"; //string InsAddConnection= InstallerBAL.GetInstallationAddressHTML2LineForEmail(Convert.ToInt32(Session[enumSessions.OrderId.ToString()].ToString())); objBuilderConnectionOnly.Replace("{InstallerAddress}", "<td><div style=\"width: 100%; margin: 0; padding: 0;\"><table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\"><tr><td style=\"text-align: left\"> <font color=\"#888\" size=\"2\" face=\"Arial\">" + InsAddConnection + " </font></td></tr></table></div></td>"); objBuilderConnectionOnly.Replace("{HeadingInstallerAdd}", "<td><h3 style=\"font-size:11px; text-align: center; margin: 0; padding: 5px auto;\">Installation Address</h3></td>"); } else { //objBuilderConnectionOnly.Replace("{InstallerAddress}", ""); // objBuilderConnectionOnly.Replace("{HeadingInstallerAdd}", ""); objBuilderConnectionOnly.Replace("{InstallerAddress}", ""); objBuilderConnectionOnly.Replace("{HeadingInstallerAdd}", ""); } // objBuilderConnectionOnly.Replace("{DeliveredTo}", OrdersBAL.GetDeliveryAddressHTML2Line(Convert.ToInt32(sendEmailDTO.orderID))); objBuilderConnectionOnly.Replace("{SpecialInstructions}", string.IsNullOrEmpty(sendEmailDTO.specialInstructions.Trim()) ? "." : sendEmailDTO.specialInstructions.Trim()); ProductsList = Regex.Replace(ProductsList, @"(?i)<(table|tr|td)(?:\s+(?:""[^""]*""|'[^']*'|[^""'>])*)?>", "<$1>"); objBuilderConnectionOnly.Replace("{ProductList}", ProductsList); LinqToSqlDataContext dbe = new LinqToSqlDataContext(); var connInstallerEmail = (from o in dbe.Orders join i in dbe.Installers on o.InstallerUnqCode equals i.UniqueCode.ToString() join ia in dbe.InstallerAddresses on i.AddressID equals ia.AddressID where o.OrderNo == OrderNo select ia.Email).Single(); if (string.IsNullOrEmpty(connInstallerEmail)) { connInstallerEmail = ConfigurationManager.AppSettings["TeleSalesEmail"].ToString(); } cslEmailMessage.From = mailFrom; cslEmailMessage.To = connInstallerEmail; cslEmailMessage.CC = mailCC; cslEmailMessage.BCC = mailCC; cslEmailMessage.Subject = mailSubjectConnectionOnly; cslEmailMessage.Message = Convert.ToString(objBuilderConnectionOnly.ToString()); sendEmail.SendEmailMessageToQueue(ConfigurationManager.AppSettings["QueueName"].ToString(), cslEmailMessage); } db.Dispose(); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception objException) { CSLOrderingARCBAL.LinqToSqlDataContext db; db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(System.Web.HttpContext.Current.Request.Url.ToString(), "SendEmailWithPrice", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } }
static void Main(string[] args) { bool Extract = false; string ArcOffset = "data.arc"; string FolderToExtract = ""; //args = new string[] { "-x", "data.arc" };//, "stage/BossStage_Dracula/normal/model/bs_dc_floor_shadow_set" }; if (args.Length == 0) { Console.WriteLine( "Notes" + "\nA lot of files/folders will not have proper filenames" + "\nCommands:" + "\nExtract entire arc (Untested! EXPERIMENTAL!!!)" + "\n-x (data.arc)" + "\nExtract folder from arc" + "\n-x (data.arc) (folderinarc)" + "\nEx: -x data.arc fighter/mario/c00"); } //process args for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-x")) { Extract = true; Console.WriteLine("Extract"); if (args.Length >= 2) { i++; ArcOffset = args[i]; Console.WriteLine(ArcOffset); if (args.Length >= 3) { i++; FolderToExtract = args[i]; Console.WriteLine(FolderToExtract); } } } } Debug.WriteLine(FolderToExtract); /*var list1 = new List<string>(); * list1.AddRange(File.ReadAllLines("moosestrings.txt")); * list1.Union(File.ReadAllLines("Hashes.txt")); * list1.Sort(); * using (StreamWriter w = new StreamWriter(new FileStream("out.txt", FileMode.Create))) * { * foreach(string s in list1) * w.WriteLine(s); * }*/ //ARC.HashCheck(); //HashDict.Init(); //ARC.CompareHashes("ARCV1_1Hashes.bin", "ARCV2_0Hashes.bin"); //return; if (!Extract) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var timer = new Stopwatch(); timer.Start(); HashDict.Init(); timer.Stop(); Debug.WriteLine("Initiating Hash Dict: " + timer.ElapsedMilliseconds); timer.Reset(); timer.Start(); ARC.Open(); timer.Stop(); Debug.WriteLine("Initiating Arc: " + timer.ElapsedMilliseconds); //ARC.CreateHashCompare("ARCV2_0Hashes.bin"); Application.Run(new Form1()); } else { //ARC.CommandFunctions(FolderToExtract); } //Console.WriteLine("Done"); //Console.WriteLine("Press enter to close"); //Console.ReadLine(); }
public static void DeleteFrom(Parse parse, SrcList tabList, Expr where_) { AuthContext sContext = new AuthContext(); // Authorization context Context ctx = parse.Ctx; // Main database structure if (parse.Errs != 0 || ctx.MallocFailed) goto delete_from_cleanup; Debug.Assert(tabList.Srcs == 1); // Locate the table which we want to delete. This table has to be put in an SrcList structure because some of the subroutines we // will be calling are designed to work with multiple tables and expect an SrcList* parameter instead of just a Table* parameter. Table table = SrcList.Lookup(parse, tabList); // The table from which records will be deleted if (table == null) goto delete_from_cleanup; // Figure out if we have any triggers and if the table being deleted from is a view #if !OMIT_TRIGGER int dummy; Trigger trigger = Triggers.Exist(parse, table, TK.DELETE, null, out dummy); // List of table triggers, if required #if OMIT_VIEW const bool isView = false; #else bool isView = (table.Select != null); // True if attempting to delete from a view #endif #else const Trigger trigger = null; bool isView = false; #endif // If pTab is really a view, make sure it has been initialized. if (sqlite3ViewGetColumnNames(parse, table) != null || IsReadOnly(parse, table, (trigger != null))) goto delete_from_cleanup; int db = sqlite3SchemaToIndex(ctx, table.Schema); // Database number Debug.Assert(db < ctx.DBs.length); string dbName = ctx.DBs[db].Name; // Name of database holding pTab ARC rcauth = Auth.Check(parse, AUTH.DELETE, table.Name, 0, dbName); // Value returned by authorization callback Debug.Assert(rcauth == ARC.OK || rcauth == ARC.DENY || rcauth == ARC.IGNORE); if (rcauth == ARC.DENY) goto delete_from_cleanup; Debug.Assert(!isView || trigger != null); // Assign cursor number to the table and all its indices. Debug.Assert(tabList.Srcs == 1); int curId = tabList.Ids[0].Cursor = parse.Tabs++; // VDBE VdbeCursor number for pTab Index idx; // For looping over indices of the table for (idx = table.Index; idx != null; idx = idx.Next) parse.Tabs++; // Start the view context if (isView) Auth.ContextPush(parse, sContext, table.Name); // Begin generating code. Vdbe v = parse.GetVdbe(); // The virtual database engine if (v == null) goto delete_from_cleanup; if (parse.Nested == 0) v.CountChanges(); parse.BeginWriteOperation(1, db); // If we are trying to delete from a view, realize that view into a ephemeral table. #if !OMIT_VIEW && !OMIT_TRIGGER if (isView) MaterializeView(parse, table, where_, curId); #endif // Resolve the column names in the WHERE clause. NameContext sNC = new NameContext(); // Name context to resolve expressions in sNC.Parse = parse; sNC.SrcList = tabList; if (sqlite3ResolveExprNames(sNC, ref where_) != 0) goto delete_from_cleanup; // Initialize the counter of the number of rows deleted, if we are counting rows. int memCnt = -1; // Memory cell used for change counting if ((ctx.Flags & Context.FLAG.CountRows) != 0) { memCnt = ++parse.Mems; v.AddOp2(OP.Integer, 0, memCnt); } #if !OMIT_TRUNCATE_OPTIMIZATION // Special case: A DELETE without a WHERE clause deletes everything. It is easier just to erase the whole table. Prior to version 3.6.5, // this optimization caused the row change count (the value returned by API function sqlite3_count_changes) to be set incorrectly. if (rcauth == ARC.OK && where_ == null && trigger == null && !IsVirtual(table) && !FKey.FkRequired(parse, table, null, 0)) { Debug.Assert(!isView); v.AddOp4(OP.Clear, table.Id, db, memCnt, table.Name, Vdbe.P4T.STATIC); for (idx = table.Index; idx != null; idx = idx.Next) { Debug.Assert(idx.Schema == table.Schema); v.AddOp2(OP.Clear, idx.Id, db); } } else #endif // The usual case: There is a WHERE clause so we have to scan through the table and pick which records to delete. { int rowSet = ++parse.Mems; // Register for rowset of rows to delete int rowid = ++parse.Mems; // Used for storing rowid values. // Collect rowids of every row to be deleted. v.AddOp2(OP.Null, 0, rowSet); ExprList dummy = null; WhereInfo winfo = Where.Begin(parse, tabList, where_, ref dummy, WHERE_DUPLICATES_OK, 0); // Information about the WHERE clause if (winfo == null) goto delete_from_cleanup; int regRowid = Expr.CodeGetColumn(parse, table, -1, curId, rowid); // Actual register containing rowids v.AddOp2(OP.RowSetAdd, rowSet, regRowid); if ((ctx.Flags & Context.FLAG.CountRows) != 0) v.AddOp2(OP.AddImm, memCnt, 1); Where.End(winfo); // Delete every item whose key was written to the list during the database scan. We have to delete items after the scan is complete // because deleting an item can change the scan order. int end = v.MakeLabel(); // Unless this is a view, open cursors for the table we are deleting from and all its indices. If this is a view, then the // only effect this statement has is to fire the INSTEAD OF triggers. if (!isView) sqlite3OpenTableAndIndices(parse, table, curId, OP.OpenWrite); int addr = v.AddOp3(OP.RowSetRead, rowSet, end, rowid); // Delete the row #if !OMIT_VIRTUALTABLE if (IsVirtual(table)) { VTable vtable = VTable.GetVTable(ctx, table); VTable.MakeWritable(parse, table); v.AddOp4(OP.VUpdate, 0, 1, rowid, vtable, Vdbe.P4T.VTAB); v.ChangeP5(OE.Abort); sqlite3MayAbort(parse); } else #endif { int count = (parse.Nested == 0; // True to count changes GenerateRowDelete(parse, table, curId, rowid, count, trigger, OE.Default); } // End of the delete loop v.AddOp2(OP.Goto, 0, addr); v.ResolveLabel(end); // Close the cursors open on the table and its indexes. if (!isView && !IsVirtual(table)) { for (int i = 1, idx = table.Index; idx != null; i++, idx = idx.Next) v.AddOp2(OP.Close, curId + i, idx.Id); v.AddOp1(OP.Close, curId); } } // Update the sqlite_sequence table by storing the content of the maximum rowid counter values recorded while inserting into // autoincrement tables. if (parse.Nested == 0 && parse.TriggerTab == null) sqlite3AutoincrementEnd(parse); // Return the number of rows that were deleted. If this routine is generating code because of a call to sqlite3NestedParse(), do not // invoke the callback function. if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.Nested == 0 && parse.TriggerTab == null) { v.AddOp2(OP.ResultRow, memCnt, 1); v.SetNumCols(1); v.SetColName(0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); } delete_from_cleanup: Auth.ContextPop(sContext); SrcList.Delete(ctx, ref tabList); Expr.Delete(ctx, ref where_); return; }
public Material ChangeColor(Illuminance Illuminance) { return(new Material(ARC.Mul(Illuminance), DRC.Mul(Illuminance), SRC.Mul(Illuminance), Shininess)); }
private void AutoLoginUser() { try { string username = Request.QueryString["User"]; string CatId = Request.QueryString["CatId"]; string userEmail = ""; if (!string.IsNullOrEmpty(username)) { if (Roles.IsUserInRole(username, enumRoles.ARCWebSite_Admin.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARCWebSite_Admin.ToString(); if (Roles.IsUserInRole(username, enumRoles.ARCWebSite_SuperAdmin.ToString())) { Session[enumSessions.IsUserSuperAdmin.ToString()] = enumRoles.ARCWebSite_SuperAdmin.ToString(); } } else { if (Roles.IsUserInRole(username, enumRoles.ARC_Manager.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARC_Manager.ToString(); } else if (Roles.IsUserInRole(username, enumRoles.ARC_Admin.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARC_Admin.ToString(); } else { lblMsg.Text = "Login unsuccessful. Please check your username and password"; System.Web.Security.FormsAuthentication.SignOut(); return; } } MembershipUser userInfo = Membership.GetUser(username); Guid UserID = new Guid(userInfo.ProviderUserKey.ToString()); userEmail = userInfo.Email; Session[enumSessions.User_Id.ToString()] = UserID; Session[enumSessions.User_Name.ToString()] = username; Session[enumSessions.User_Email.ToString()] = userEmail; // if (Session[enumSessions.User_Role.ToString()] == enumRoles.ARCWebSite_Admin.ToString()) // Response.Redirect("ADMIN/AdminDefault.aspx"); ARC arc = ArcBAL.GetArcInfoByUserId(new Guid(Session[enumSessions.User_Id.ToString()].ToString())); if (arc == null) { lblMsg.Text = "Login denied! Your account is not related to any ARC. Please contact CSL DualCom."; System.Web.Security.FormsAuthentication.SignOut(); return; } Session[enumSessions.ARC_Id.ToString()] = arc.ARCId; Session[enumSessions.IsARC_AllowReturns.ToString()] = arc.AllowReturns; LinqToSqlDataContext db = new LinqToSqlDataContext(); var OrderInfo = db.USP_CreateOrderForUser(arc.ARCId, Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Email.ToString()].ToString(), Session[enumSessions.User_Id.ToString()].ToString()).SingleOrDefault(); if (OrderInfo != null) { Session[enumSessions.OrderId.ToString()] = OrderInfo.OrderId; Session[enumSessions.OrderNumber.ToString()] = OrderInfo.OrderNo.ToString(); Session[enumSessions.HasUserAcceptedDuplicates.ToString()] = OrderInfo.HasUserAcceptedDuplicates; if (OrderInfo.InstallerId != "0") { Session[enumSessions.InstallerCompanyID.ToString()] = OrderInfo.InstallerId; Session[enumSessions.SelectedInstaller.ToString()] = OrderInfo.SelectedInstaller; } } db.Dispose(); FormsAuthentication.SetAuthCookie(username, false); //if (Session[enumSessions.IsARC_AllowReturns.ToString()] != null && Convert.ToBoolean(Session[enumSessions.IsARC_AllowReturns.ToString()])) // Response.Redirect("UploadOrder.aspx"); //else if (string.IsNullOrEmpty(CatId) || CatId.Trim() == "") { Response.Redirect("Categories.aspx"); } else { Response.Redirect("ProductList.aspx?CategoryId=" + CatId); } } } catch (System.Threading.ThreadAbortException ex) { // } catch (Exception objException) { CSLOrderingARCBAL.LinqToSqlDataContext db; db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(Request.Url.ToString(), "AutoLoginUser", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } }
protected void MyLogin_Authenticate(object sender, AuthenticateEventArgs e) { try { lblMsg.Text = ""; string username = cslLogin.UserName; string userEmail = ""; if (AuthenticateUser(username, cslLogin.Password)) { if (Roles.IsUserInRole(username, enumRoles.ARCWebSite_Admin.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARCWebSite_Admin.ToString(); if (Roles.IsUserInRole(username, enumRoles.ARCWebSite_SuperAdmin.ToString())) { Session[enumSessions.IsUserSuperAdmin.ToString()] = enumRoles.ARCWebSite_SuperAdmin.ToString(); } } else { if (Roles.IsUserInRole(username, enumRoles.ARC_Manager.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARC_Manager.ToString(); } else if (Roles.IsUserInRole(username, enumRoles.ARC_Admin.ToString())) { Session[enumSessions.User_Role.ToString()] = enumRoles.ARC_Admin.ToString(); } else { e.Authenticated = false; lblMsg.Text = "Login unsuccessful. Please check your username and password"; System.Web.Security.FormsAuthentication.SignOut(); // e.Cancel = true; return; } } MembershipUser userInfo = Membership.GetUser(username); Guid UserID = new Guid(userInfo.ProviderUserKey.ToString()); userEmail = userInfo.Email; Session[enumSessions.User_Id.ToString()] = UserID; Session[enumSessions.User_Name.ToString()] = username; Session[enumSessions.User_Email.ToString()] = userEmail; ARC arc = ArcBAL.GetArcInfoByUserId(new Guid(Session[enumSessions.User_Id.ToString()].ToString())); if (arc == null) { e.Authenticated = false; lblMsg.Text = "Login denied! Your account is not related to any ARC. Please contact CSL DualCom."; System.Web.Security.FormsAuthentication.SignOut(); // e.Cancel = true; Session[enumSessions.User_Id.ToString()] = null; return; } Session[enumSessions.ARC_Id.ToString()] = arc.ARCId; Session[enumSessions.IsARC_AllowReturns.ToString()] = arc.AllowReturns; LinqToSqlDataContext db = new LinqToSqlDataContext(); var OrderInfo = db.USP_CreateOrderForUser(arc.ARCId, Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Name.ToString()].ToString(), Session[enumSessions.User_Email.ToString()].ToString(), Session[enumSessions.User_Id.ToString()].ToString()).SingleOrDefault(); if (OrderInfo != null) { Session[enumSessions.OrderId.ToString()] = OrderInfo.OrderId; Session[enumSessions.OrderNumber.ToString()] = OrderInfo.OrderNo.ToString(); Session[enumSessions.HasUserAcceptedDuplicates.ToString()] = OrderInfo.HasUserAcceptedDuplicates; if (OrderInfo.InstallerId != "0") { Session[enumSessions.InstallerCompanyID.ToString()] = OrderInfo.InstallerId; Session[enumSessions.SelectedInstaller.ToString()] = OrderInfo.SelectedInstaller; } } e.Authenticated = true; db.Dispose(); } else { e.Authenticated = false; lblMsg.Text = "Login unsuccessful ! unable to find your details"; System.Web.Security.FormsAuthentication.SignOut(); // e.Cancel = true; return; } } catch (System.Threading.ThreadAbortException ex) { // } catch (Exception objException) { CSLOrderingARCBAL.LinqToSqlDataContext db; db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(Request.Url.ToString(), "cslLogin_LoggingIn", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } }
public Form1() { InitializeComponent(); fileTree.BeforeExpand += folderTree_BeforeExpand; fileTree.NodeMouseClick += (sender, args) => fileTree.SelectedNode = args.Node; fileTree.HideSelection = false; fileTree.ImageList = new ImageList(); fileTree.ImageList.Images.Add("folder", Properties.Resources.folder); fileTree.ImageList.Images.Add("file", Properties.Resources.file); regionCB.SelectedIndex = 0; //initialize arc // BGM /*foreach(_sBGMOffset off in ARC.BGMOffsets) * { * BGM.Nodes.Add(new FileNode(off.Offset.ToString("X")) * { * ArcOffset = off.Offset, * DecompSize = (uint)off.Size, * CompSize = (uint)off.Size * }); * }*/ // Files long TotalSize = 0; var timer = new Stopwatch(); timer.Start(); if (ARC.FileInformation != null || ARC.FileInformationV2 != null) { foreach (FileOffsetGroup g in ARC.GetFiles()) { FolderNode Folder = (FolderNode)GetFolderFromPath(g.Path, Root); if (g.CompSize == null) { continue; } FileNode fNode = new FileNode(g.FileName) { ArcOffset = g.ArcOffset[0], CompSize = (uint)g.CompSize[0], DecompSize = (uint)g.DecompSize[0], Flags = g.Flags[0],//(uint)g.SubFileInformationOffset FullFilePath = g.Path + g.FileName }; if ((g.ArcOffset.Length > 1)) { fNode.IsRegional = true; fNode._rArcOffset = g.ArcOffset; fNode._rCompSize = g.CompSize; fNode._rDecompSize = g.DecompSize; fNode._rFlags = g.Flags; fNode.FullFilePath = g.Path + g.FileName; } TotalSize += fNode.DecompSize; Folder.SubNodes.Add(fNode); } } foreach (var g in ARC.GetStreamFiles()) { string FPath = g.FileName.Replace("stream:/", ""); FolderNode Folder = (FolderNode)GetFolderFromPath(Path.GetDirectoryName(FPath).Replace("\\", "/"), Stream); FileNode fNode = new FileNode(Path.GetFileName(FPath)) { ArcOffset = g.ArcOffset[0], CompSize = (uint)g.CompSize[0], DecompSize = (uint)g.DecompSize[0], Flags = g.Flags[0], FullFilePath = FPath }; if ((g.ArcOffset.Length > 1)) { fNode.IsRegional = true; fNode._rArcOffset = g.ArcOffset; fNode._rCompSize = g.CompSize; fNode._rDecompSize = g.DecompSize; fNode._rFlags = g.Flags; fNode.FullFilePath = FPath; } Folder.SubNodes.Add(fNode); } timer.Stop(); Debug.WriteLine("To load files into tree: " + timer.ElapsedMilliseconds); Debug.WriteLine("Total File Size: " + FormatBytes(TotalSize)); /*string[] folders = ARC.GetPaths(); * foreach(string s in folders) * { * //fileTree.Nodes.Add(new TreeNode(s)); * MKDir(s); * }*/ //update /*foreach (_sDirectoryList h in ARC.DirectoryLists) * { * _sFileInformation[] fi = ARC.GetFileInformationFromFolder(h); * string path = ARC.GetPathString(ARC.FolderHashDict, h); * foreach (_sFileInformation i in fi) * { * //MKDir(path + "/" + ARC.GetName(i.Unk4)); * TreeNode Folder = GetFolderFromPath(path + "/" + ARC.GetName(i.Parent)); * //_SubFileInfo sub = ARC.SubFileInformation_1[i.SubFile1_Index]; * ARC.FileOffsetGroup group = ARC.GetOffsetFromSubFile(i); * * Folder.Nodes.Add(new FileNode(ARC.GetName(i.Hash2)) * { * ArcOffset = group.ArcOffset, * CompSize = (uint)group.CompSize, * DecompSize = (uint)group.DecompSize, * Flags = group.Flags * }); * } * }*/ fileTree.BeginUpdate(); fileTree.Nodes.Add(Root); fileTree.Nodes.Add(Stream); fileTree.EndUpdate(); //DumpWithExtension(".nuanmb"); }
public static void sqlite3Update(Parse parse, SrcList tabList, ExprList changes, Expr where_, OE onError) { int i, j; // Loop counters AuthContext sContext = new AuthContext(); // The authorization context Context ctx = parse.Ctx; // The database structure if (parse.Errs != 0 || ctx.MallocFailed) { goto update_cleanup; } Debug.Assert(tabList.Srcs == 1); // Locate the table which we want to update. Table table = sqlite3SrcListLookup(parse, tabList); // The table to be updated if (table == null) { goto update_cleanup; } int db = sqlite3SchemaToIndex(ctx, table.Schema); // Database containing the table being updated // Figure out if we have any triggers and if the table being updated is a view. #if !OMIT_TRIGGER int tmask = 0; // Mask of TRIGGER_BEFORE|TRIGGER_AFTER Trigger trigger = sqlite3TriggersExist(parse, table, TK.UPDATE, changes, out tmask); // List of triggers on pTab, if required #if OMIT_VIEW const bool isView = false; #else bool isView = (table.Select != null); // True when updating a view (INSTEAD OF trigger) #endif Debug.Assert(trigger != null || tmask == 0); #else const Trigger trigger = null; const int tmask = 0; const bool isView = false; #endif if (sqlite3ViewGetColumnNames(parse, table) != 0 || sqlite3IsReadOnly(parse, table, tmask)) { goto update_cleanup; } int[] xrefs = new int[table.Cols.length]; // xrefs[i] is the index in pChanges->a[] of the an expression for the i-th column of the table. xrefs[i]==-1 if the i-th column is not changed. if (xrefs == null) { goto update_cleanup; } for (i = 0; i < table.Cols.length; i++) { xrefs[i] = -1; } // Allocate a cursors for the main database table and for all indices. The index cursors might not be used, but if they are used they // need to occur right after the database cursor. So go ahead and allocate enough space, just in case. int curId; // VDBE Cursor number of pTab tabList.Ids[0].Cursor = curId = parse.Tabs++; Index idx; // For looping over indices for (idx = table.Index; idx != null; idx = idx.Next) { parse.Tabs++; } // Initialize the name-context NameContext sNC = new NameContext(); // The name-context to resolve expressions in sNC.Parse = parse; sNC.SrcList = tabList; // Resolve the column names in all the expressions of the of the UPDATE statement. Also find the column index // for each column to be updated in the pChanges array. For each column to be updated, make sure we have authorization to change that column. bool chngRowid = false; // True if the record number is being changed Expr rowidExpr = null; // Expression defining the new record number for (i = 0; i < changes.Exprs; i++) { if (sqlite3ResolveExprNames(sNC, ref changes.Ids[i].Expr) != 0) { goto update_cleanup; } for (j = 0; j < table.Cols.length; j++) { if (string.Equals(table.Cols[j].Name, changes.Ids[i].Name, StringComparison.OrdinalIgnoreCase)) { if (j == table.PKey) { chngRowid = true; rowidExpr = changes.Ids[i].Expr; } xrefs[j] = i; break; } } if (j >= table.Cols.length) { if (Expr::IsRowid(changes.Ids[i].Name)) { chngRowid = true; rowidExpr = changes.Ids[i].Expr; } else { parse.ErrorMsg("no such column: %s", changes.Ids[i].Name); parse.CheckSchema = 1; goto update_cleanup; } } #if !OMIT_AUTHORIZATION { ARC rc = Auth.Check(parse, AUTH.UPDATE, table.Name, table.Cols[j].Name, ctx.DBs[db].Name); if (rc == ARC.DENY) { goto update_cleanup; } else if (rc == ARC.IGNORE) { xrefs[j] = -1; } } #endif } bool hasFK = sqlite3FkRequired(parse, table, xrefs, chngRowid ? 1 : 0); // True if foreign key processing is required // Allocate memory for the array aRegIdx[]. There is one entry in the array for each index associated with table being updated. Fill in // the value with a register number for indices that are to be used and with zero for unused indices. int idxLength; // Number of indices that need updating for (idxLength = 0, idx = table.Index; idx != null; idx = idx.Next, idxLength++) { ; } int[] regIdxs = null; // One register assigned to each index to be updated if (idxLength > 0) { regIdxs = new int[idxLength]; if (regIdxs == null) { goto update_cleanup; } } for (j = 0, idx = table.Index; idx != null; idx = idx.Next, j++) { int regId; if (hasFK || chngRowid) { regId = ++parse.Mems; } else { regId = 0; for (i = 0; i < idx.Columns.length; i++) { if (xrefs[idx.Columns[i]] >= 0) { regId = ++parse.Mems; break; } } } regIdxs[j] = regId; } // Begin generating code. Vdbe v = parse.GetVdbe(); // The virtual database engine if (v == null) { goto update_cleanup; } if (parse.Nested == 0) { v.CountChanges(); } parse.BeginWriteOperation(1, db); #if !OMIT_VIRTUALTABLE // Virtual tables must be handled separately if (IsVirtual(table)) { UpdateVirtualTable(parse, tabList, table, changes, rowidExpr, xrefs, where_, onError); where_ = null; tabList = null; goto update_cleanup; } #endif // Register Allocations int regRowCount = 0; // A count of rows changed int regOldRowid; // The old rowid int regNewRowid; // The new rowid int regNew; int regOld = 0; int regRowSet = 0; // Rowset of rows to be updated // Allocate required registers. regOldRowid = regNewRowid = ++parse.Mems; if (trigger != null || hasFK) { regOld = parse.Mems + 1; parse.Mems += table.Cols.length; } if (chngRowid || trigger != null || hasFK) { regNewRowid = ++parse.Mems; } regNew = parse.Mems + 1; parse.Mems += table.Cols.length; // Start the view context. if (isView) { Auth.ContextPush(parse, sContext, table.Name); } // If we are trying to update a view, realize that view into a ephemeral table. #if !OMIT_VIEW && !OMIT_TRIGGER if (isView) { sqlite3MaterializeView(parse, table, where_, curId); } #endif // Resolve the column names in all the expressions in the WHERE clause. if (sqlite3ResolveExprNames(sNC, ref where_) != 0) { goto update_cleanup; } // Begin the database scan v.AddOp2(OP.Null, 0, regOldRowid); ExprList dummy = null; WhereInfo winfo = Where.Begin(parse, tabList, where_, ref dummy, WHERE.ONEPASS_DESIRED); // Information about the WHERE clause if (winfo == null) { goto update_cleanup; } bool okOnePass = winfo.OkOnePass; // True for one-pass algorithm without the FIFO // Remember the rowid of every item to be updated. v.AddOp2(OP.Rowid, curId, regOldRowid); if (!okOnePass) { v.AddOp2(OP.RowSetAdd, regRowSet, regOldRowid); } // End the database scan loop. Where.End(winfo); // Initialize the count of updated rows if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null) { regRowCount = ++parse.Mems; v.AddOp2(OP.Integer, 0, regRowCount); } bool openAll = false; // True if all indices need to be opened if (!isView) { // Open every index that needs updating. Note that if any index could potentially invoke a REPLACE conflict resolution // action, then we need to open all indices because we might need to be deleting some records. if (!okOnePass) { sqlite3OpenTable(parse, curId, db, table, OP.OpenWrite); } if (onError == OE.Replace) { openAll = true; } else { openAll = false; for (idx = table.Index; idx != null; idx = idx.Next) { if (idx.OnError == OE.Replace) { openAll = true; break; } } } for (i = 0, idx = table.Index; idx != null; idx = idx.Next, i++) { if (openAll || regIdxs[i] > 0) { KeyInfo key = sqlite3IndexKeyinfo(parse, idx); v.AddOp4(OP.OpenWrite, curId + i + 1, idx.Id, db, key, Vdbe.P4T.KEYINFO_HANDOFF); Debug.Assert(parse.Tabs > curId + i + 1); } } } // Top of the update loop int addr = 0; // VDBE instruction address of the start of the loop if (okOnePass) { int a1 = v.AddOp1(OP.NotNull, regOldRowid); addr = v.AddOp0(OP.Goto); v.JumpHere(a1); } else { addr = v.AddOp3(OP.RowSetRead, regRowSet, 0, regOldRowid); } // Make cursor iCur point to the record that is being updated. If this record does not exist for some reason (deleted by a trigger, // for example, then jump to the next iteration of the RowSet loop. v.AddOp3(OP.NotExists, curId, addr, regOldRowid); // If the record number will change, set register regNewRowid to contain the new value. If the record number is not being modified, // then regNewRowid is the same register as regOldRowid, which is already populated. Debug.Assert(chngRowid || trigger != null || hasFK || regOldRowid == regNewRowid); if (chngRowid) { Expr.Code(parse, rowidExpr, regNewRowid); v.AddOp1(OP.MustBeInt, regNewRowid); } // If there are triggers on this table, populate an array of registers with the required old.* column data. if (hasFK || trigger != null) { uint oldmask = (hasFK ? sqlite3FkOldmask(parse, table) : 0); oldmask |= sqlite3TriggerColmask(parse, trigger, changes, 0, TRIGGER_BEFORE | TRIGGER_AFTER, table, onError); for (i = 0; i < table.Cols.length; i++) { if (xrefs[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i)))) { Expr.CodeGetColumnOfTable(v, table, curId, i, regOld + i); } else { v.AddOp2(OP.Null, 0, regOld + i); } } if (!chngRowid) { v.AddOp2(OP.Copy, regOldRowid, regNewRowid); } } // Populate the array of registers beginning at regNew with the new row data. This array is used to check constaints, create the new // table and index records, and as the values for any new.* references made by triggers. // // If there are one or more BEFORE triggers, then do not populate the registers associated with columns that are (a) not modified by // this UPDATE statement and (b) not accessed by new.* references. The values for registers not modified by the UPDATE must be reloaded from // the database after the BEFORE triggers are fired anyway (as the trigger may have modified them). So not loading those that are not going to // be used eliminates some redundant opcodes. int newmask = (int)sqlite3TriggerColmask(parse, trigger, changes, 1, TRIGGER_BEFORE, table, onError); // Mask of NEW.* columns accessed by BEFORE triggers for (i = 0; i < table.Cols.length; i++) { if (i == table.PKey) { //v.AddOp2(OP.Null, 0, regNew + i); } else { j = xrefs[i]; if (j >= 0) { Expr.Code(parse, changes.Ids[j].Expr, regNew + i); } else if ((tmask & TRIGGER_BEFORE) == 0 || i > 31 || (newmask & (1 << i)) != 0) { // This branch loads the value of a column that will not be changed into a register. This is done if there are no BEFORE triggers, or // if there are one or more BEFORE triggers that use this value via a new.* reference in a trigger program. C.ASSERTCOVERAGE(i == 31); C.ASSERTCOVERAGE(i == 32); v.AddOp3(OP.Column, curId, i, regNew + i); v.ColumnDefault(table, i, regNew + i); } } } // Fire any BEFORE UPDATE triggers. This happens before constraints are verified. One could argue that this is wrong. if ((tmask & TRIGGER_BEFORE) != 0) { v.AddOp2(OP.Affinity, regNew, table.Cols.length); sqlite3TableAffinityStr(v, table); sqlite3CodeRowTrigger(parse, trigger, TK.UPDATE, changes, TRIGGER_BEFORE, table, regOldRowid, onError, addr); // The row-trigger may have deleted the row being updated. In this case, jump to the next row. No updates or AFTER triggers are // required. This behavior - what happens when the row being updated is deleted or renamed by a BEFORE trigger - is left undefined in the documentation. v.AddOp3(OP.NotExists, curId, addr, regOldRowid); // If it did not delete it, the row-trigger may still have modified some of the columns of the row being updated. Load the values for // all columns not modified by the update statement into their registers in case this has happened. for (i = 0; i < table.Cols.length; i++) { if (xrefs[i] < 0 && i != table.PKey) { v.AddOp3(OP.Column, curId, i, regNew + i); v.ColumnDefault(table, i, regNew + i); } } } if (!isView) { // Do constraint checks. int dummy2; sqlite3GenerateConstraintChecks(parse, table, curId, regNewRowid, regIdxs, (chngRowid ? regOldRowid : 0), true, onError, addr, out dummy2); // Do FK constraint checks. if (hasFK) { sqlite3FkCheck(parse, table, regOldRowid, 0); } // Delete the index entries associated with the current record. int j1 = v.AddOp3(OP.NotExists, curId, 0, regOldRowid); // Address of jump instruction sqlite3GenerateRowIndexDelete(parse, table, curId, regIdxs); // If changing the record number, delete the old record. if (hasFK || chngRowid) { v.AddOp2(OP.Delete, curId, 0); } v.JumpHere(j1); if (hasFK) { sqlite3FkCheck(parse, table, 0, regNewRowid); } // Insert the new index entries and the new record. sqlite3CompleteInsertion(parse, table, curId, regNewRowid, regIdxs, true, false, false); // Do any ON CASCADE, SET NULL or SET DEFAULT operations required to handle rows (possibly in other tables) that refer via a foreign key // to the row just updated. if (hasFK) { sqlite3FkActions(parse, table, changes, regOldRowid); } } // Increment the row counter if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null) { v.AddOp2(OP.AddImm, regRowCount, 1); } sqlite3CodeRowTrigger(parse, trigger, TK.UPDATE, changes, TRIGGER_AFTER, table, regOldRowid, onError, addr); // Repeat the above with the next record to be updated, until all record selected by the WHERE clause have been updated. v.AddOp2(OP.Goto, 0, addr); v.JumpHere(addr); // Close all tables Debug.Assert(regIdxs != null); for (i = 0, idx = table.Index; idx != null; idx = idx.Next, i++) { if (openAll || regIdxs[i] > 0) { v.AddOp2(OP.Close, curId + i + 1, 0); } } v.AddOp2(OP.Close, curId, 0); // Update the sqlite_sequence table by storing the content of the maximum rowid counter values recorded while inserting into // autoincrement tables. if (parse.Nested == 0 && parse.TriggerTab == null) { sqlite3AutoincrementEnd(parse); } // Return the number of rows that were changed. If this routine is generating code because of a call to sqlite3NestedParse(), do not // invoke the callback function. if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null && parse.Nested == 0) { v.AddOp2(OP.ResultRow, regRowCount, 1); v.SetNumCols(1); v.SetColName(0, COLNAME_NAME, "rows updated", SQLITE_STATIC); } update_cleanup: #if !OMIT_AUTHORIZATION Auth.ContextPop(sContext); #endif C._tagfree(ctx, ref regIdxs); C._tagfree(ctx, ref xrefs); SrcList.Delete(ctx, ref tabList); ExprList.Delete(ctx, ref changes); Expr.Delete(ctx, ref where_); return; }