public static int Main(string[] args) { int status = 0; try { Console.Out.Write("testing Slice predefined macros... "); Console.Out.Flush(); Default d = new Default(); test(d.x == 10); test(d.y == 10); NoDefault nd = new NoDefault(); test(nd.x != 10); test(nd.y != 10); CsOnly c = new CsOnly(); test(c.lang.Equals("cs")); test(c.version == Ice.Util.intVersion()); Console.Out.WriteLine("ok"); } catch(System.Exception ex) { Console.Error.WriteLine(ex); status = 1; } return status; }
// Get an entire entity set. static void ListAllProducts(Default.Container container) { foreach (var p in container.Products) { Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category); } }
public ISO9141(ICommbox box) : base(box) { options = null; kLine = SK_NO; lLine = RK_NO; func = new Default<ISO9141>(box, this); }
public KWP2000(ICommbox box) : base(box) { this.func = new Default<KWP2000>(box, this); StartCommunicationInit(); kLine = SK_NO; lLine = RK_NO; }
static void AddProduct(Default.Container container, ProductService.Models.Product product) { container.AddToProducts(product); var serviceResponse = container.SaveChanges(); foreach (var operationResponse in serviceResponse) { Console.WriteLine("Response: {0}", operationResponse.StatusCode); } }
public static MethodSig Read(BinaryStreamReader signatureBlobReader) { var callingConvention = (CallingConventions)signatureBlobReader.ReadByte(); MethodSig result; switch (callingConvention & ~CallingConventions.HasThis & ~CallingConventions.ExplicitThis) { case CallingConventions.Default: result = new Default(); break; case CallingConventions.C: result = new C(); break; case CallingConventions.StdCall: result = new StdCall(); break; case CallingConventions.FastCall: result = new FastCall(); break; case CallingConventions.VarArg: result = new VarArg(); break; case CallingConventions.Generic: { var typed = new Generic(); typed.ReadDetails(signatureBlobReader); result = typed; } break; default: throw new BadImageFormatException("Invalid calling convention byte "+callingConvention+"."); } result.ReadParameters(signatureBlobReader); return result; }
/// <summary> /// Initializes a new BoxCutter for debugging. /// </summary> /// <param name="sortType">True if you want the logs written to be sorted by writer, false if you want them to be written /// chronologically. If true, the buffer has to be flushed when the game closes; if it closes unexpectedly the file may /// be empty. Also, it keeps everything written in memory; this could become massive fast.</param> /// <param name="overwriteOldLogs">True if you want the log to save to debug.log, false if you want the date and time appended /// to the filename.</param> public BoxCutter(bool sortLogs, bool overwriteOldLogs, string savePath) { #if DEBUG || TRACE string path; this.sortLogs = sortLogs; overwriteLogs = overwriteOldLogs; d = new Default(); n = new NonFatalException(); f = new FatalException(); if(overwriteOldLogs) { path = savePath + "debug.log"; if(File.Exists(path)) file = File.Open(path, FileMode.Truncate); else file = File.Open(path, FileMode.CreateNew); } else { IEnumerable<string> filenames = Directory.EnumerateFiles(savePath, "debug*.log"); int debuglogs = filenames.Count<string>(); if(debuglogs > 9) { int logstodelete = debuglogs - 9; for(int i = 0; i < logstodelete; i++) try { File.Delete(filenames.ElementAt(i)); } catch { } } path = savePath + "debug[" + DateTime.Now.ToShortDateString().Replace(@"/", @"-").Replace(@"\", @"-") + "][" + DateTime.Now.ToLongTimeString().Replace(@":", @".") + "].log"; file = File.Open(path, FileMode.Create); } writer = new StreamWriter(file); if(sortLogs) { sortedBuffer = new Dictionary<object, List<string>>(); sortedBuffer.Add(d, new List<string>()); sortedBuffer.Add(n, new List<string>()); sortedBuffer.Add(f, new List<string>()); } #endif }
public IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags) { return(Default.CreateGLContext(handle, window, shareContext, directRendering, major, minor, flags)); }
public INativeWindow CreateNativeWindow(int x, int y, int width, int height, string title, GraphicsMode mode, GameWindowFlags options, DisplayDevice device) { return(Default.CreateNativeWindow(x, y, width, height, title, mode, options, device)); }
private void Init() { _glSerialisable = new GameLogicSerialisable(); Counter = 0; _default = new Default( ); _increment = new Increment( ); _decrement = new Decrement( ); }
/// <summary> /// Deletes all mappings, etc. Basically clears out everything so you can recreate items (only really useful for testing) /// </summary> public static void Destroy() { Company.Utilities.SQL.SQLHelper.ClearAllMappings(); Reflection.AOP.AOPManager.Destroy(); MappingManager = null; QueryProvider = null; DatabaseManager = null; }
public InvoiceViewModel() { Invoice = new Invoice(); DefaultSetting = new Default(); }
public void RegisterResource(IDisposable resource) { Default.RegisterResource(resource); }
protected void RegisterOnlineChecker(Default page) { this.RegisterType<Bll.UserStatusChecking.IUserInfo, Default.UserStatusCheckAdapter.UserInfoProvider>(new InjectionConstructor(page)); this.RegisterType<IResultHandler, Default.UserStatusCheckAdapter.ResultHandler>(new InjectionConstructor(page)); }
protected internal override void TraverseDefault(Default @default) { Types.Add(@default, @default.Type); }
/// <summary> /// Calculates an approximate normal vector for the vertices of indexed geometry. /// <para> </para> /// This function calculates one normal vector per inputted triangle and then averages together the normal vectors for any <para/> /// shared vertices. /// </summary> /// <param name="vertices">An array of vertices that build out the geometry.</param> /// <param name="indices">The indices used to properly sequence the vertex array.</param> public static void CalculateVertexNormals(ref Default[] vertices, uint[] indices) { List<Vector3>[] normarray = new List<Vector3>[vertices.Length]; uint idx1, idx2, idx3; for (int a = 0; a < indices.Length; a += 3) { idx1 = indices[a]; idx2 = indices[a + 1]; idx3 = indices[a + 2]; if (normarray[idx1] == null) { normarray[idx1] = new List<Vector3>(); } if (normarray[idx2] == null) { normarray[idx2] = new List<Vector3>(); } if (normarray[idx3] == null) { normarray[idx3] = new List<Vector3>(); } Vector3 diff1 = vertices[idx2].Position - vertices[idx1].Position; Vector3 diff2 = vertices[idx3].Position - vertices[idx1].Position; Vector3 diff3 = vertices[idx3].Position - vertices[idx2].Position; Vector3 diff4 = vertices[idx1].Position - vertices[idx2].Position; Vector3 diff5 = vertices[idx1].Position - vertices[idx3].Position; Vector3 diff6 = vertices[idx2].Position - vertices[idx3].Position; normarray[idx1].Add(-Vector3.Normalize(Vector3.Cross(diff1, diff2))); normarray[idx2].Add(-Vector3.Normalize(Vector3.Cross(diff3, diff4))); normarray[idx3].Add(-Vector3.Normalize(Vector3.Cross(diff5, diff6))); } for (int a = 0; a < normarray.Length; a++) { Vector3 ctsum = Vector3.Zero; for (int b = 0; b < normarray[a].Count; b++) ctsum += normarray[a][b]; vertices[a].Normal = ctsum / normarray[a].Count; } }
/// <summary> /// Calculate the normal vector for each vertex in a vertex array. /// <para>Assumes the vertex array can be parsed in groups of three (as in sequential triangles).</para> /// <para>Therefore, shared vertices are not supported. Normal vectors are automatically normalized.</para> /// </summary> /// <param name="vertices">An array of vertices that build triangles sequentially.</param> public static void CalculateVertexNormals(ref Default[] vertices) { for (int a = 0; a < vertices.Length; a += 3) { Vector3 diff1 = vertices[a + 1].Position - vertices[a].Position; Vector3 diff2 = vertices[a + 2].Position - vertices[a].Position; Vector3 diff3 = vertices[a + 2].Position - vertices[a + 1].Position; Vector3 diff4 = vertices[a].Position - vertices[a + 1].Position; Vector3 diff5 = vertices[a].Position - vertices[a + 2].Position; Vector3 diff6 = vertices[a + 1].Position - vertices[a + 2].Position; vertices[a].Normal = -Vector3.Normalize(Vector3.Cross(diff1, diff2)); vertices[a + 1].Normal = -Vector3.Normalize(Vector3.Cross(diff3, diff4)); vertices[a + 2].Normal = -Vector3.Normalize(Vector3.Cross(diff5, diff6)); } }
public override void VisitDefaultCaseLabel(Default p) { throw new InvalidOperationException(); }
public IKeyboardDriver2 CreateKeyboardDriver() { return(Default.CreateKeyboardDriver()); }
protected internal override Node TransformDefault(Default @default) { return Dispatch(@default); }
public IGamePadDriver CreateGamePadDriver() { return(Default.CreateGamePadDriver()); }
protected void RegisterMailChecker(Default page) { this.RegisterType<Bll.UserMailChecking.IUserInfo, Default.UserMailCheckAdapter.UserInfoProvider>(new InjectionConstructor(page)); this.RegisterType<IResultHandler<MailRepository.MailInfo>, Default.UserMailCheckAdapter.ResultHandler> (new InjectionConstructor(page, new ResolvedParameter<Bll.UserMailChecking.IUserInfo>())); }
/// <summary> /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes. /// </summary> /// <param name="context">The modified document context.</param> /// <param name="previous">The original document model.</param> /// <returns>A list of messages from the comparison.</returns> public override IEnumerable <ComparisonMessage> Compare( ComparisonContext <ServiceDefinition> context, T previous ) { var prior = previous; if (prior == null) { throw new ArgumentNullException("priorVersion"); } if (context == null) { throw new ArgumentNullException("context"); } base.Compare(context, previous); if (Reference != null && !Reference.Equals(prior.Reference)) { context.LogBreakingChange(ComparisonMessages.ReferenceRedirection); } if (IsRequired != prior.IsRequired) { if (context.Direction != DataDirection.Response) { if (IsRequired && !prior.IsRequired) { context.LogBreakingChange(ComparisonMessages.RequiredStatusChange, prior.IsRequired, IsRequired); } else { context.LogInfo(ComparisonMessages.RequiredStatusChange, prior.IsRequired, IsRequired); } } } // Are the types the same? if (prior.Type.HasValue != Type.HasValue || (Type.HasValue && prior.Type.Value != Type.Value)) { context.LogBreakingChange(ComparisonMessages.TypeChanged, Type.HasValue ? Type.Value.ToString().ToLower() : "", prior.Type.HasValue ? prior.Type.Value.ToString().ToLower() : ""); } // What about the formats? CompareFormats(context, prior); CompareItems(context, prior); if (Default != null && !Default.Equals(prior.Default) || (Default == null && !string.IsNullOrEmpty(prior.Default))) { context.LogBreakingChange(ComparisonMessages.DefaultValueChanged); } if (Type.HasValue && Type.Value == DataType.Array && prior.CollectionFormat != CollectionFormat) { context.LogBreakingChange(ComparisonMessages.ArrayCollectionFormatChanged); } CompareConstraints(context, prior); CompareProperties(context, prior); CompareEnums(context, prior); return(context.Messages); }
public override int GetHashCode(T obj) { return(Default.GetHashCode(obj)); }
private void Setup(Assembly Assembly) { MappingManager = new MappingManager(Assembly); QueryProvider = new Default(Assembly); foreach (Type Key in MappingManager.Mappings.Keys) foreach (IMapping Mapping in MappingManager.Mappings[Key]) QueryProvider.AddMapping(Mapping); Utilities.Reflection.AOP.AOPManager Manager = new Reflection.AOP.AOPManager(); Manager.AddAspect(new ORMAspect(MappingManager.Mappings)); DatabaseManager = new DatabaseManager(QueryProvider.Mappings); DatabaseManager.Setup(); }
protected internal override Node TransformDefault(Default @default) { return(Dispatch(@default)); }
public Mikuni(ICommbox box) : base(box) { this.func = new Default<Mikuni>(box, this); }
public async Task A_console_project_can_be_used_to_get_type_completion_with_a_space_in_the_name() { await Default.ConsoleWorkspace(); #region bufferSources var program = @"using System; using System.Linq; namespace FibonacciTest { public class Program { public static void Main() { foreach (var i in FibonacciGenerator.Fibonacci().Take(20)) { Console.WriteLine(i); } } } }".EnforceLF(); var generator = @"using System.Collections.Generic; using System; namespace FibonacciTest { public static class FibonacciGenerator { public static IEnumerable<int> Fibonacci() { int current = 1, next = 1; while (true) { yield return current; next = current + (current = next); Cons$$ } } } }".EnforceLF(); #endregion var package = await PackageUtilities.Copy(await Default.ConsoleWorkspace(), "a space"); var(processed, position) = CodeManipulation.ProcessMarkup(generator); var log = new LogEntryList(); using (LogEvents.Subscribe(log.Add)) using (var agent = new AgentService()) { var json = new WorkspaceRequest(activeBufferId: "generators/FibonacciGenerator.cs", requestId: "TestRun", workspace: Workspace.FromSources( package.Name, language: "csharp", ("Program.cs", program, 0), ("generators/FibonacciGenerator.cs", processed, position) )).ToJson(); var request = new HttpRequestMessage( HttpMethod.Post, @"/workspace/completion") { Content = new StringContent( json, Encoding.UTF8, "application/json") }; var response = await agent.SendAsync(request); var result = await response .EnsureSuccess() .DeserializeAs <CompletionResult>(); result.Items.Should().NotBeNullOrEmpty(); result.Items.Should().Contain(completion => completion.SortText == "Console"); } }
public static async Task FlushAsync(int waitMilliseconds = 1) { await Default.FlushAsync(waitMilliseconds); }
protected internal override void TraverseDefault(Default @default) { var t = @default.Type; _writer.Write("default({0})", t == null ? "?" : t.GetCSharpRef(ToCSharpOptions.Informative)); }
private static DataRepositorySettings CreateDefaultSettings(DirectoryInfo directory) { return(Create(Default.DataRepositorySettings(directory))); }
static Default() { Context = new Default(); }
public async Task A_console_workspace_can_be_used_to_get_signature_help() { await Default.ConsoleWorkspace(); #region bufferSources var program = @"using System; using System.Linq; namespace FibonacciTest { public class Program { public static void Main() { foreach (var i in FibonacciGenerator.Fibonacci().Take(20)) { Console.WriteLine(i); } } } }".EnforceLF(); var generator = @"using System.Collections.Generic; using System; namespace FibonacciTest { public static class FibonacciGenerator { public static IEnumerable<int> Fibonacci() { int current = 1, next = 1; while (true) { yield return current; next = current + (current = next); Console.WriteLine($$); } } } }".EnforceLF(); #endregion var(processed, position) = CodeManipulation.ProcessMarkup(generator); var log = new LogEntryList(); using (LogEvents.Subscribe(log.Add)) using (var agent = new AgentService()) { var json = new WorkspaceRequest(activeBufferId: "generators/FibonacciGenerator.cs", requestId: "TestRun", workspace: Workspace.FromSources( workspaceType: "console", language: "csharp", ("Program.cs", program, 0), ("generators/FibonacciGenerator.cs", processed, position) )).ToJson(); var request = new HttpRequestMessage( HttpMethod.Post, @"/workspace/signaturehelp") { Content = new StringContent( json, Encoding.UTF8, "application/json") }; var response = await agent.SendAsync(request); var result = await response .EnsureSuccess() .DeserializeAs <SignatureHelpResult>(); result.Signatures.Should().NotBeNullOrEmpty(); result.Signatures.Should().Contain(diagnostic => diagnostic.Label == "void Console.WriteLine(string format, params object[] arg)"); } }
/// <summary> /// Deletes all mappings, etc. Basically clears out everything so you can recreate items (only really useful for testing) /// </summary> public static void Destroy() { Utilities.SQL.MicroORM.MicroORM.ClearAllMappings(); Reflection.AOP.AOPManager.Destroy(); MappingManager = null; QueryProvider = null; DatabaseManager = null; }
public async Task A_console_project_can_be_used_to_get_diagnostics() { await Default.ConsoleWorkspace(); #region bufferSources var program = @"using System; using System.Linq; namespace FibonacciTest { public class Program { public static void Main() { foreach (var i in FibonacciGenerator.Fibonacci().Take(20)) { Console.WriteLine(i); } } } }".EnforceLF(); var generator = @"using System.Collections.Generic; using System; namespace FibonacciTest { public static class FibonacciGenerator { public static IEnumerable<int> Fibonacci() { int current = 1, next = 1; while (true) { adddd yield return current; next = current + (current = next); Cons$$ } } } }".EnforceLF(); #endregion var(processed, position) = CodeManipulation.ProcessMarkup(generator); var log = new LogEntryList(); using (LogEvents.Subscribe(log.Add)) using (var agent = new AgentService()) { var json = new WorkspaceRequest(activeBufferId: "generators/FibonacciGenerator.cs", requestId: "TestRun", workspace: Workspace.FromSources( "console", language: "csharp", ("Program.cs", program, 0), ("generators/FibonacciGenerator.cs", processed, position) )).ToJson(); var request = new HttpRequestMessage( HttpMethod.Post, @"/workspace/diagnostics") { Content = new StringContent( json, Encoding.UTF8, "application/json") }; var response = await agent.SendAsync(request); var result = await response .EnsureSuccess() .DeserializeAs <DiagnosticResult>(); result.Diagnostics.Should().NotBeNullOrEmpty(); result.Diagnostics.Should().Contain(diagnostic => diagnostic.Message == "generators/FibonacciGenerator.cs(12,17): error CS0246: The type or namespace name \'adddd\' could not be found (are you missing a using directive or an assembly reference?)"); } }
protected override Assembly Load(AssemblyName assemblyName) => _loaderTask.LoadAssemblyByName(assemblyName) ?? Default.LoadFromAssemblyName(assemblyName);
public IDisplayDeviceDriver CreateDisplayDeviceDriver() { return(Default.CreateDisplayDeviceDriver()); }
/// <summary> /// Write instruction operands into bytecode stream. /// </summary> /// <param name="writer">Bytecode writer.</param> public override void WriteOperands(WordWriter writer) { Selector.Write(writer); Default.Write(writer); Target.Write(writer); }
public GraphicsContext.GetCurrentContextDelegate CreateGetCurrentGraphicsContext() { return(Default.CreateGetCurrentGraphicsContext()); }
protected override Assembly Load(AssemblyName assemblyName) { return(Default.LoadFromAssemblyName(assemblyName)); }
public IMouseDriver2 CreateMouseDriver() { return(Default.CreateMouseDriver()); }
public static List <ATTEvaluationCriteria> GetEvaluationCriteriaList(int?grpID, Default defGrade, string active) { List <ATTEvaluationCriteria> lst = new List <ATTEvaluationCriteria>(); try { List <ATTEvaluationCriteriaGrade> lstGrade = BLLEvaluationCriteriaGrade.GetEvaluationCriteriaGradeList("", active); foreach (DataRow row in DLLEvaluationCriteria.GetEvaluationCriteriaTable(grpID, active).Rows) { ATTEvaluationCriteria obj = new ATTEvaluationCriteria(); obj.EvaluationCriteriaID = int.Parse(row["Eval_crit_id"].ToString()); obj.FromDate = row["from_date"].ToString(); obj.GroupID = int.Parse(row["Eval_group_id"].ToString()); obj.EvaluationCriteriaName = row["eval_crit_name"].ToString(); obj.ToDate = row["to_date"].ToString(); obj.Active = row["active"].ToString(); obj.Action = "N"; obj.LstEvaluationCriteriaGrade = lstGrade.FindAll ( delegate(ATTEvaluationCriteriaGrade grade) { return(grade.EvaluationCriteriaID == obj.EvaluationCriteriaID && grade.FromDate == obj.FromDate); } ); if (defGrade == Default.Yes) { ATTEvaluationCriteriaGrade defaultGrade = new ATTEvaluationCriteriaGrade(); defaultGrade.EvaluationGradeName = "----- भार छन्नुहोस -----"; obj.LstEvaluationCriteriaGrade.Insert(0, defaultGrade); } lst.Add(obj); } return(lst); } catch (Exception ex) { throw ex; } }
public IJoystickDriver2 CreateJoystickDriver() { return(Default.CreateJoystickDriver()); }
protected void Page_Load(object sender, EventArgs e) { Response.Write("进入认证界面<br/>"); if (!IsPostBack) { Random rad = new Random(); int iRad = rad.Next(1000, 100000); if (!string.IsNullOrEmpty(Request["state"])) { #region state不为空 string state = Request["state"]; //Response.Write("state:" + state); try { #region 参数拼成 Loggers.Debug(new DebugLogInfo() { Message = string.Format("strState2: {0}", state) }); //byte[] buff1 = Convert.FromBase64String(state); //state = Encoding.UTF8.GetString(buff1); //state = HttpUtility.UrlDecode(state, Encoding.UTF8); //string[] array = state.Split(','); //customerId = array[0]; //applicationId = array[1]; //goUrl = array[2]; //goUrl = goUrlTemp + goUrl; byte[] buff1 = Convert.FromBase64String(state); state = Encoding.UTF8.GetString(buff1); state = HttpUtility.UrlDecode(state, Encoding.UTF8); string[] array = state.Split(','); customerId = array[1]; applicationId = array[2]; goUrl = array[0]; #endregion } catch (Exception ex) { Response.Write("<br/>"); Response.Write("state错误:" + ex.ToString()); } #endregion } else { #region 参数 //判断客户ID是否传递 if (!string.IsNullOrEmpty(Request["customerId"])) { customerId = Request["customerId"]; } else { Response.Write("<br>"); Response.Write("没有获取客户标识"); } if (!string.IsNullOrEmpty(Request["applicationId"])) { applicationId = Request["applicationId"]; } else { loggingSessionInfo = Default.GetBSLoggingSession(customerId, "1"); var list = new WApplicationInterfaceBLL(loggingSessionInfo).QueryByEntity(new WApplicationInterfaceEntity { CustomerId = customerId }, null).ToList(); if (list != null && list.Count > 0) { applicationId = list.FirstOrDefault().ApplicationId; } else { Response.Write("<br>"); Response.Write("没有获取微信标识,请联系管理员尽快处理."); Response.End(); } } if (!string.IsNullOrEmpty(Request["goUrl"])) { goUrl = Request["goUrl"]; Response.Write("<br>"); Response.Write("goUrl:" + goUrl); string eventId = Request["eventId"]; if (eventId != null && !eventId.Equals("")) { if (goUrl.IndexOf("?") > 0) { goUrl = goUrl + "&eventId=" + eventId + ""; } else { goUrl = goUrl + "?eventId=" + eventId + ""; } } //Response.End(); } else { Response.Write("<br>"); Response.Write("没有获取goUrl"); Response.End(); } #endregion } Response.Write("<br>"); Response.Write("goUrl:" + goUrl); //Response.End(); loggingSessionInfo = Default.GetBSLoggingSession(customerId, "1"); //Get keys about Wechat GetKey(); string code = Request["code"]; if (code == null || code.Equals("")) { //strState = customerId + "," + applicationId + "," + goUrl; // //strState = HttpUtility.UrlEncode(strState, Encoding.UTF8); //byte[] buff = Encoding.UTF8.GetBytes(strState); //strState = Convert.ToBase64String(buff); strState = goUrl + "," + customerId + "," + applicationId; // strState = HttpUtility.UrlEncode(strState, Encoding.UTF8); byte[] buff = Encoding.UTF8.GetBytes(strState); strState = Convert.ToBase64String(buff); authBll.GetOAuthCode(strAppId, strRedirectUri, strState, this.Response); } else { Response.Write("存在code:" + code); string token = ""; string openId = authBll.GetAccessToken(code, strAppId, strAppSecret, loggingSessionInfo, iRad, out token); Response.Write("<br>"); Response.Write("OpenID:" + openId); PageRedict(openId); } } }
protected override Assembly Load(AssemblyName assemblyName) { return(this.loaderTask.LoadAssemblyByName(assemblyName) ?? Default.LoadFromAssemblyName(assemblyName)); }
private void addVendor_Click(object sender, EventArgs e) { String name = nameTextBox.Text.ToString(); String address = addressTextBox.Text.ToString(); long phoneNumber = (long)this.phoneNumber.Value; if (String.IsNullOrEmpty(name)) { Default.ShowError("Name for vendor cannot be empty!"); return; } if (String.IsNullOrEmpty(address)) { Default.ShowError("Address for vendor cannot be empty!"); return; } if (store1.Count == 0) { if ( MessageBox.Show( "You linked \"NO\" products to the vendor\n" + "Maybe you might have missed doing following: \n" + "1. Clicking \"Assign Product to Vendor\" Button\n" + "If not linking any product was what you intended, hit OK." , "No Links", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { return; } } //That is all what is required when creating a record for a vendor, but what follows is a more //important stuff, particularly the one which help in creating a many-to-many relationship SqlCommand command = connection.CreateCommand(); command.CommandText = //"BEGIN TRANSACTION;" + "INSERT INTO Vendor VALUES(@name,@address,@phone)"; command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@address", address); command.Parameters.AddWithValue("@phone", phoneNumber); try { if (command.ExecuteNonQuery() > 0) { if (store1.Count > 0) { SqlCommand command_c = connection.CreateCommand(); command_c.CommandText = "SELECT IDENT_CURRENT('Vendor') AS \"SCOPE_IDENTITY\";"; //Found this on microsoft website, as a good solution to get the last identity value generated across current scope SqlDataReader reader = command_c.ExecuteReader(); if (reader.Read()) { int identity = (int)((decimal)reader["SCOPE_IDENTITY"]); //Identity is the current working auto_increment reader.Close(); int l = AddIntoMappingTable(store1, identity); if ((l) == store1.Count) { Default.ShowInfo(String.Format("The Vendor \"{0}\" has now been added, and linked to {1} products.", name, l), "SUCCESS"); } else { Default.ShowError("Failure when adding records to the MappingTable, inserted: " + l, "FAILURE"); } } else { Default.ShowError("Could not get the identity for the last row inserted"); } if (!reader.IsClosed) { reader.Close(); } } else { Default.ShowInfo( String.Format("The Vendor {0} has now been added but is not linked to any product(s).", name), "SUCCESS"); } } else { MessageBox.Show("Fatal error, cannot add record to the database", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (SqlException) { Default.ShowError("UNIQUE KEY violation, you cannot have two vendors with same name"); } }
private void Settings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Default.Save(); }
private void deleteButton_Click(object sender, EventArgs e) { int vendorID = (int)deleteNumericUpDown.Value; //This is the critical section of the code, as here we are deleting all the vendor information, and all the product info that is linked to the vendor //We must all tell our user that we have unlinked (x) number of product references from deleting the vendor SqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT COUNT(*) as \"count_total\" FROM MappingTable WHERE VendorID = @vendorID"; command.Parameters.AddWithValue("@vendorID", vendorID); SqlDataReader reader = command.ExecuteReader(); int records = 0; DialogResult result = DialogResult.Yes; if (reader.Read() && (records = (int)reader["count_total"]) > 0) { result = MessageBox.Show( String.Format("This vendor is currently serving {0} products.\n" + "Deleting the vendor will also delete all link data.\n" + "Are you sure?", records), "CONFIRMATION", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } reader.Close(); if (result == DialogResult.Yes)//since no change will happens to result if hasRows is false, this will always be executed { String delete = "DELETE FROM PurchaseOrder WHERE VendorID = @vendorID;" + "DELETE FROM Vendor WHERE VendorID = @vendorID;"; command.CommandText = records > 0 ? "DELETE FROM MappingTable WHERE VendorID = @vendorID;" : delete; //No confirmation, no questions asked, just purge the record //There is a problem here as teh vendor records are purged from the mapping table, they are not removed from the vendor table //Try splitting the statement into two statements;/or try vendorID param to change to vendorID2, NO!!! if (command.ExecuteNonQuery() > 0) { bool success = true; if (records > 0) { command.CommandText = delete; if (!(command.ExecuteNonQuery() > 0)) { success = false; } } if (success) { MessageBox.Show(String.Format( "We have purged the vendor record clean, ID:{0}, Links:{1}" , vendorID, records), "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information); } DataTable dataTable = ((DataTable)deletePageGridView.DataSource); if (dataTable != null && dataTable.Rows.Count > lastPointer) { dataTable.Rows[lastPointer].Delete(); } } else { Default.ShowError("No Vendor exists for given ID"); } } }
protected internal override void TraverseDefault(Default @default) { Dispatch(@default); }
static CssBackgroundFeature() { Default.Freeze(); }
private static void Setup(bool Profile, Assembly[] Assemblies) { MappingManager = new MappingManager(Assemblies); QueryProvider = new Default(Profile, Assemblies); foreach (Type Key in MappingManager.Mappings.Keys) foreach (IMapping Mapping in MappingManager.Mappings[Key]) QueryProvider.AddMapping(Mapping); Company.Utilities.Reflection.AOP.AOPManager Manager = new Reflection.AOP.AOPManager(); Manager.AddAspect(new ORMAspect(MappingManager.Mappings)); DatabaseManager = new DatabaseManager(QueryProvider.Mappings); DatabaseManager.Setup(); }
private static Fixed8 CalculateBonusInternal(IEnumerable <SpentCoin> unclaimed) { Fixed8 amount_claimed = Fixed8.Zero; foreach (var group in unclaimed.GroupBy(p => new { p.StartHeight, p.EndHeight })) { uint amount = 0; uint ustart = group.Key.StartHeight / DecrementInterval; if (ustart < GenerationAmount.Length) { uint istart = group.Key.StartHeight % DecrementInterval; uint uend = group.Key.EndHeight / DecrementInterval; uint iend = group.Key.EndHeight % DecrementInterval; if (uend >= GenerationAmount.Length) { uend = (uint)GenerationAmount.Length; iend = 0; } if (iend == 0) { uend--; iend = DecrementInterval; } while (ustart < uend) { amount += (DecrementInterval - istart) * GenerationAmount[ustart]; ustart++; istart = 0; } amount += (iend - istart) * GenerationAmount[ustart]; } amount += (uint)(Default.GetSysFeeAmount(group.Key.EndHeight - 1) - (group.Key.StartHeight == 0 ? 0 : Default.GetSysFeeAmount(group.Key.StartHeight - 1))); amount_claimed += group.Sum(p => p.Value) / 100000000 * amount; } return(amount_claimed); }
protected internal virtual void TraverseDefault(Default @default) { @default.Unsupported(); }
public static void Fatal(string message, LogLevel level = LogLevel.Fatal, [CallerMemberName] string callerMemberName = null, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) { Default.Fatal(message, level, callerMemberName, callerFilePath, callerLineNumber); }
private void AddTableButton_Click(object sender, System.EventArgs e) { Database db; Table tbl; Column col; Index idx; Default dflt; Cursor csr = null; try { csr = this.Cursor; // Save the old cursor this.Cursor = Cursors.WaitCursor; // Display the waiting cursor // Show the current tables for the selected database db = (Database)DatabasesComboBox.SelectedItem; if (db.Tables.Contains(TableNameTextBox.Text) == false) { // Create an empty string default dflt = db.Defaults["dfltEmptyString"]; if (dflt == null) { dflt = new Default(db, "dfltEmptyString"); dflt.TextHeader = "CREATE DEFAULT [dbo].[dfltEmptyString] AS "; dflt.TextBody = @"'';"; dflt.Create(); } // Create a new table object tbl = new Table(db, TableNameTextBox.Text, db.DefaultSchema); // Add the first column col = new Column(tbl, @"Column1", DataType.Int); tbl.Columns.Add(col); col.Nullable = false; col.Identity = true; col.IdentitySeed = 1; col.IdentityIncrement = 1; // Add the primary key index idx = new Index(tbl, @"PK_" + TableNameTextBox.Text); tbl.Indexes.Add(idx); idx.IndexedColumns.Add(new IndexedColumn(idx, col.Name)); idx.IsClustered = true; idx.IsUnique = true; idx.IndexKeyType = IndexKeyType.DriPrimaryKey; // Add the second column col = new Column(tbl, @"Column2", DataType.NVarChar(1024)); tbl.Columns.Add(col); col.DataType.MaximumLength = 1024; col.AddDefaultConstraint(null); // Use SQL Server default naming col.DefaultConstraint.Text = Properties.Resources.DefaultConstraintText; col.Nullable = false; // Add the third column col = new Column(tbl, @"Column3", DataType.DateTime); tbl.Columns.Add(col); col.Nullable = false; // Create the table tbl.Create(); // Refresh list and select the one we just created ShowTables(); // Clear selected items TablesComboBox.SelectedIndex = -1; // Find the table just created TablesComboBox.SelectedIndex = TablesComboBox.FindStringExact(tbl.ToString()); } else { ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = string.Format(System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.TableExists, TableNameTextBox.Text); emb.Show(this); } } catch (SmoException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } finally { this.Cursor = csr; // Restore the original cursor } }
protected internal virtual Node TransformDefault(Default @default) { return @default.AcceptTransformer(this, true); }