private static void Main() { string[] mainMenu = { "Задание 1. Использовать коолекцию Stack", "Задание 2. Работа с обобщенной коллекцией SortedDictionary", "Задание 3. Создание своей коллекции Queue", "Выход" }; while (true) { var sw = Use.Menu(0, "Здравствуйте! Выберите задание:", mainMenu); switch (sw) { case 1: var stack = new StackWork(); stack.Start(); break; case 2: var dictionary = new SortedDictionaryWork(); dictionary.Start(); break; case 3: var queue = new MyQueueWork(); queue.Start(); break; case 4: return; } } }
private OperationResult <T> ExecuteWrapper <T>(string sql, CommandType commandType, IEnumerable <KeyValuePair <string, object> > parameters, Func <string, CommandType, IEnumerable <KeyValuePair <string, object> >, OperationResult <T> > callback) { var operation = callback(sql, commandType, parameters); System.Threading.Tasks.Task.Run(() => Use.StringBuilder(builder => { builder.AppendLine(); builder.Append(DataOrderFormatter.Format(new AliasedCommandTypeDataOrder(sql, commandType, parameters))); builder.AppendLine(); if (operation.WasSuccessful) { builder.AppendLine("Operation completed successfully."); } else { builder.AppendLine("Operation was unsuccessful."); if (operation.HadErrors) { builder.AppendLine(); builder.AppendLine("Operation was faulted."); builder.AppendLine(); builder.AppendLine(DefaultExceptionFormatter.FormatException(operation.Exceptions)); } } builder.AppendLine(); builder.AppendLine(new string('*', 120)); _logger.Log(builder); }) ); return(operation); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["id"])) { Use u = new Use(); u = Use.Fetch(Convert.ToInt32(Request.QueryString["id"].ToString())); txtFirstname.Text = u.UserFname; txtSecondname.Text = u.UserLname; txtAddress1.Text = u.UserAdd1; txtAddress2.Text = u.UserAdd2; txtCity.Text = u.UserCity; DdlState.SelectedIndex = u.StateID; // Double check this txtZip.Text = u.UserZip; txtUsername.Text = u.UserName; txtPassword.Text = u.UserPassword; txtConfirmPass.Text = u.UserPassword; txtEmail.Text = u.UserEmail; txtConfirmEmail.Text = u.UserEmail; txtPhone.Text = u.UserPhone; rblIsActive.SelectedValue = u.Active.ToString(); } } }
public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) { var document = new Use(mapping.DocumentType); method.Frames.Code($"if ({{0}}.{mapping.IdMember.Name} <= 0) {{0}}.Id = \"{_mapping.Alias}\"/ + {{1}}.Sequences.SequenceFor({{2}}).NextLong();", document, Use.Type <ITenant>(), mapping.DocumentType); method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); }
public static void DeserializeAsync(this FramesCollection frames, IDocumentMapping mapping) { var documentType = mapping.DocumentType; var document = new Variable(documentType, DocumentVariableName); if (mapping is DocumentMapping d) { if (!d.IsHierarchy()) { frames.Code($@" {documentType.FullNameInCode()} document; BLOCK:using (var json = reader.GetTextReader(0)) document = _serializer.FromJson<{documentType.FullNameInCode()}>(json); END ").Creates(document); } else { frames.CodeAsync($@" {documentType.FullNameInCode()} document; var typeAlias = await reader.GetFieldValueAsync<string>(2, {{0}}).ConfigureAwait(false); BLOCK:using (var json = reader.GetTextReader(0)) document = ({documentType.FullNameInCode()}) _serializer.FromJson(_mapping.TypeFor(typeAlias), json); END ", Use.Type <CancellationToken>()).Creates(document); } } }
static void Main(string[] argc) { Use use = new Use(); int x = 80; Console.WriteLine("输出的结果是: " + use.Test(x)); }
/// <summary> /// The Use ability has started or stopped using an item. /// </summary> /// <param name="start">Has the Use ability started?</param> /// <param name="useAbility">The Use ability that has started or stopped.</param> private void OnUseStart(bool start, Use useAbility) { if (useAbility.FaceTargetItem != null) { m_FaceUseTargetCount += start ? 1 : -1; } }
public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) { var use = new Use(mapping.DocumentType); method.Frames.Code("if ({0}." + mapping.IdMember.Name + " == null) _setter({0}, global::" + typeof(ShortGuid).FullNameInCode() + ".NewGuid());", use); method.Frames.Code("return {0}." + mapping.IdMember.Name + ";", use); }
private void Start() { if (transform.parent.GetComponentInChildren <Use>() != null) { use = transform.parent.GetComponentInChildren <Use>(); } }
//Меню private void TypeQueries() { string[] queriesMenu = { "Запросы к типу Worker", "Запросы к типу Engineer", "Запросы к типу Administration", "Назад" }; while (true) { var sw = Use.Menu(0, "Выберите нужный пункт:", queriesMenu); switch (sw) { case 1: Queries <Worker>(); break; case 2: Queries <Engineer>(); break; case 3: Queries <Administration>(); break; case 4: return; } } }
public void CanWriteJoinsToDatabase() { using (var process = CreateDslInstance("Dsl/InnerHashJoin.boo")) { process.Execute(); } List <string> roles = new List <string>(); Use.Transaction(TestDatabase.ConnectionString, cmd => { cmd.CommandText = @" SELECT Roles FROM Users WHERE Roles IS NOT NULL ORDER BY Id "; using (IDataReader reader = cmd.ExecuteReader()) while (reader.Read()) { roles.Add(reader.GetString(0)); } }); Assert.Equal("ayende rahien is: [admin, janitor, employee, customer]", roles[0]); Assert.Equal("foo bar is: [janitor]", roles[1]); Assert.Equal("gold silver is: [janitor, employee]", roles[2]); }
/// <summary> /// Validate the organization name /// </summary> /// <remarks> /// An organization name is valid if: /// <list type="bullet"> /// <item>All validation rules from <see cref="T:MARC.Everest.DataTypes.EN"/> are satisfied</item> /// <item>The <see cref="Use"/> property is not one of {Indigenous, Pseudonym, Anonymous, Artist, Religious, MaidenName }</item> /// <item>The <see cref="F:MARC.Everest.DataTypes.ENXP.Type"/> property of each <see cref="Part"/> is not in { Given, Family }</item> /// </list> /// </remarks> public override bool Validate() { bool isValid = base.Validate(); List <EntityNamePartType> disallowedPartTypes = new List <EntityNamePartType>() { EntityNamePartType.Given, EntityNamePartType.Family }; List <EntityNameUse?> disallowedUses = new List <EntityNameUse?>() { EntityNameUse.Indigenous, EntityNameUse.Pseudonym, EntityNameUse.Anonymous, EntityNameUse.Artist, EntityNameUse.Religious, EntityNameUse.MaidenName }; //object obj = disallowedQualifiers.Find(o => Use.Find(u => u.Code.Equals(o)) != null); if (Use != null) { isValid &= !disallowedUses.Exists(o => Use.Find(u => u.Code.Equals(o)) != null); } // Validate parts foreach (var part in Part) { isValid &= !disallowedPartTypes.Contains(part.Type.HasValue ? part.Type.Value : EntityNamePartType.Title); } return(isValid); }
/// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable, int timeout) : this(Use.ConnectionString(connectionStringName), targetTable, timeout) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; }
private bool Handle(Use command) { if (_redemptions <= 0) { return(true); } var use = _credits < 100 ? _credits : _rng.Next(_credits); var dice = _rng.Next(100); if (dice < 95) { _aggregateManager.Tell(new RedeemCommand(_id, use)); _credits = _credits - use; if (_credits > 0) { var time = TimeSpan.FromSeconds(_rng.NextDouble() * 60); Context.GetLogger().Info($"[{_id}] redeemed with [{use}]credits, sending another Use in [{time.Seconds}s]"); Context.System.Scheduler.ScheduleTellOnce(time, Self, new Use(), Self); } _redemptions--; } else { _aggregateManager.Tell(new CancelCommand(_id)); Context.GetLogger().Warning($"[{_id}] cancelled with [{_credits}]credits left."); _redemptions = 0; } return(true); }
public OperationResult <byte[]> MakeWebRequest(string url, IEnumerable <Tuple <string, string> > data, IEnumerable <Tuple <HttpRequestHeader, string> > requestHeaders) { WebLoggingToBegin?.Invoke(this, new Utilities.EventArgs.GenericEventArgs <IFileNameSwappable>(_logger)); string webRequest = Use.StringBuilder(builder => { builder.AppendLine("***** WEB REQUEST *****"); builder.AppendLine(); builder.AppendLine($"URL : {url}"); if (data.Any()) { builder.AppendLine($"Data :"); builder.Append(string.Join("\r\n", data.Where(d => string.IsNullOrWhiteSpace(d.Item2) == false).Select(d => $"\t{d.Item1} :\r\n\t\t{string.Join("\\r\\n", d.Item2.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))}"))); } if (requestHeaders.Any()) { builder.AppendLine($"Request Headers :"); builder.Append(string.Join("\r\n", requestHeaders.Select(d => $"\t{d.Item1} :\r\n\t\t{d.Item2}"))); } builder.AppendLine(); builder.AppendLine("***** END *****"); }); OperationResult loggingOperation = _logger.Log(webRequest); if (loggingOperation.WasSuccessful) { WebLoggingCompletedSuccessfully?.Invoke(this, new Utilities.EventArgs.GenericEventArgs <string>(_logger.FileName)); return(new OperationResult <byte[]>(loggingOperation.Exceptions)); } return(new OperationResult <byte[]>(Response)); }
public void GenerateCode(GeneratedMethod assign, DocumentMapping mapping) { var document = new Use(mapping.DocumentType); assign.Frames.Code($"_setter({{0}}, \"newId\");", document); assign.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); }
/// <summary> /// Executes this operation /// </summary> /// <param name="rows">The rows.</param> /// <returns></returns> public override IEnumerable <Row> Execute(IEnumerable <Row> rows) { using (IDbConnection connection = Use.Connection(ConnectionStringSettings)) using (IDbTransaction transaction = BeginTransaction(connection)) { foreach (Row row in new SingleRowEventRaisingEnumerator(this, rows)) { using (IDbCommand cmd = connection.CreateCommand()) { currentCommand = cmd; currentCommand.Transaction = transaction; PrepareCommand(currentCommand, row); currentCommand.ExecuteNonQuery(); } } if (PipelineExecuter.HasErrors) { Warn("Rolling back transaction in {0}", Name); transaction.Rollback(); Warn("Rolled back transaction in {0}", Name); } else { Debug("Committing {0}", Name); if (transaction != null) { transaction.Commit(); } Debug("Committed {0}", Name); } } yield break; }
private static GeneratedType buildInsertStream(GeneratedType builderType, GeneratedAssembly generatedAssembly, EventGraph graph) { var operationType = generatedAssembly.AddType(InsertStreamOperationName, typeof(InsertStreamBase)); var columns = new StreamsTable(graph) .Columns .OfType <IStreamTableColumn>() .Where(x => x.Writes) .ToArray(); var sql = $"insert into {graph.DatabaseSchemaName}.mt_streams ({columns.Select(x => x.Name).Join(", ")}) values ({columns.Select(_ => "?").Join(", ")})"; var configureCommand = operationType.MethodFor("ConfigureCommand"); configureCommand.DerivedVariables.Add(new Variable(typeof(StreamAction), nameof(InsertStreamBase.Stream))); configureCommand.Frames.Code($"var parameters = {{0}}.{nameof(CommandBuilder.AppendWithParameters)}(\"{sql}\");", Use.Type <CommandBuilder>()); for (var i = 0; i < columns.Length; i++) { columns[i].GenerateAppendCode(configureCommand, i); } builderType.MethodFor(nameof(EventDocumentStorage.InsertStream)) .Frames.Code($"return new Marten.Generated.{InsertStreamOperationName}(stream);"); return(operationType); }
private void ChangeMode() { EndState?.Invoke(); bool isGolfing = false; if (CurrentMode == Mode.Golfing || CurrentMode == Mode.Null) { CurrentMode = Mode.Running; EnterState = EnterRunState; UpdateState = UpdateRunState; EndState = EndRunState; PrimaryUseStart = RunPrimaryUseStart; PrimaryUseHeld = RunPrimaryUseHeld; PrimaryUseEnd = RunPrimaryUseEnd; SecondaryUseStart = RunSecondaryUseStart; SecondaryUseHeld = RunSecondaryUseHeld; SecondaryUseEnd = RunSecondaryUseEnd; } else if (CurrentMode == Mode.Running) { CurrentMode = Mode.Golfing; isGolfing = true; EnterState = EnterClubState; UpdateState = UpdateClubState; EndState = EndClubState; PrimaryUseStart = ClubPrimaryUseStart; PrimaryUseHeld = ClubPrimaryUseHeld; PrimaryUseEnd = ClubPrimaryUseEnd; SecondaryUseStart = ClubSecondaryUseStart; SecondaryUseHeld = ClubSecondaryUseHeld; SecondaryUseEnd = ClubSecondaryUseEnd; } playerGolf.SetGolfMode(isGolfing); EventController.FireEvent(new ModeChangedMessage(isGolfing)); EnterState(); }
private static void buildConfigureCommandMethodForStreamState(EventGraph graph, GeneratedType streamQueryHandlerType) { var sql = $"select id, version, type, timestamp, created as timestamp, is_archived from {graph.DatabaseSchemaName}.mt_streams where id = ?"; if (graph.TenancyStyle == TenancyStyle.Conjoined) { streamQueryHandlerType.AllInjectedFields.Add(new InjectedField(typeof(string), "tenantId")); sql += $" and {TenantIdColumn.Name} = ?"; } var configureCommand = streamQueryHandlerType.MethodFor("ConfigureCommand"); configureCommand.Frames.Call <CommandBuilder>(x => x.AppendWithParameters(""), @call => { @call.Arguments[0] = Constant.ForString(sql); @call.ReturnAction = ReturnAction.Initialize; }); var idDbType = graph.StreamIdentity == StreamIdentity.AsGuid ? DbType.Guid : DbType.String; configureCommand.Frames.Code("{0}[0].Value = _streamId;", Use.Type <NpgsqlParameter[]>()); configureCommand.Frames.Code("{0}[0].DbType = {1};", Use.Type <NpgsqlParameter[]>(), idDbType); if (graph.TenancyStyle == TenancyStyle.Conjoined) { configureCommand.Frames.Code("{0}[1].Value = _tenantId;", Use.Type <NpgsqlParameter[]>()); configureCommand.Frames.Code("{0}[1].DbType = {1};", Use.Type <NpgsqlParameter[]>(), DbType.String); } }
private static GeneratedType buildAppendEventOperation(EventGraph graph, GeneratedAssembly assembly) { var operationType = assembly.AddType("AppendEventOperation", typeof(AppendEventOperationBase)); var configure = operationType.MethodFor(nameof(AppendEventOperationBase.ConfigureCommand)); configure.DerivedVariables.Add(new Variable(typeof(IEvent), nameof(AppendEventOperationBase.Event))); configure.DerivedVariables.Add(new Variable(typeof(StreamAction), nameof(AppendEventOperationBase.Stream))); var columns = new EventsTable(graph).SelectColumns() // Hokey, use an explicit model for writeable vs readable columns some day .Where(x => !(x is IsArchivedColumn)).ToList(); var sql = $"insert into {graph.DatabaseSchemaName}.mt_events ({columns.Select(x => x.Name).Join(", ")}) values ({columns.Select(_ => "?").Join(", ")})"; configure.Frames.Code($"var parameters = {{0}}.{nameof(CommandBuilder.AppendWithParameters)}(\"{sql}\");", Use.Type <CommandBuilder>()); for (var i = 0; i < columns.Count; i++) { columns[i].GenerateAppendCode(configure, graph, i); } return(operationType); }
private void buildStorageOperationMethods(DocumentOperations operations, GeneratedType type) { buildOperationMethod(type, operations, "Upsert"); buildOperationMethod(type, operations, "Insert"); buildOperationMethod(type, operations, "Update"); if (_mapping.UseOptimisticConcurrency) { buildOperationMethod(type, operations, "Overwrite"); } else { type.MethodFor("Overwrite").Frames.ThrowNotSupportedException(); } type.MethodFor("DeleteForDocument").Frames.Code($@" return new Marten.Generated.{operations.DeleteById.TypeName}(Identity({{0}})); ", new Use(_mapping.DocumentType)); type.MethodFor("DeleteForId").Frames.Code($@" return new Marten.Generated.{operations.DeleteById.TypeName}({{0}}); ", new Use(_mapping.IdType)); type.MethodFor("DeleteForWhere").Frames.Code($@" return new Marten.Generated.{operations.DeleteByWhere.TypeName}({{0}}); ", Use.Type <IWhereFragment>()); }
// TODO -- just inject the type alias and simplify the operation classes private void buildOperationMethod(GeneratedType type, DocumentOperations operations, string methodName) { var operationType = (GeneratedType)typeof(DocumentOperations).GetProperty(methodName).GetValue(operations); var method = type.MethodFor(methodName); if (_mapping.IsHierarchy()) { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>(), {{2}} );" , new Use(_mapping.DocumentType), Use.Type <IMartenSession>(), Use.Type <DocumentMapping>()); } else { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>() );" , new Use(_mapping.DocumentType), Use.Type <IMartenSession>()); } }
/// <summary> /// Executes this operation /// </summary> public override IEnumerable <Row> Execute(IEnumerable <Row> rows) { Guard.Against <ArgumentException>(rows == null, "SqlBulkInsertOperation cannot accept a null enumerator"); PrepareSchema(); PrepareMapping(); CreateInputSchema(); using (SqlConnection connection = (SqlConnection)Use.Connection(ConnectionStringSettings)) using (SqlTransaction transaction = BeginTransaction(connection)) { sqlBulkCopy = CreateSqlBulkCopy(connection, transaction); DictionaryEnumeratorDataReader adapter = new DictionaryEnumeratorDataReader(_inputSchema, rows); sqlBulkCopy.WriteToServer(adapter); if (PipelineExecuter.HasErrors) { Warn("Rolling back transaction in {0}", Name); if (transaction != null) { transaction.Rollback(); } Warn("Rolled back transaction in {0}", Name); } else { Debug("Committing {0}", Name); if (transaction != null) { transaction.Commit(); } Debug("Committed {0}", Name); } } yield break; }
static IEnumerable <Route> ServeRequest(Request request) { (IGraphDatabase cars, IGraphDatabase trains) = MockData.InitDatabases(); /* * * Add request handling here and return calculated route * */ IRequestHandler requestHandler = Use.RequestValidator(); requestHandler .Then(Use.Resolver(new CostResolver())) .Then(Use.Resolver(new TimeResolver())) .Then(Catch.UnresolvedProblem()) .Then(Use.Database(cars, VehicleType.Car)) .Then(Use.Database(trains, VehicleType.Train)) .Then(Catch.NullDatabase()) .Then(Use.Filter(new PopulationFilter())) .Then(Use.Filter(new RestaurantFilter())) .Then(Use.Solver(new DijkstraSolver(), "Dijkstra")) .Then(Use.Solver(new DFSSolver(), "DFS")) .Then(Use.Solver(new BFSSolver(), "BFS")); return(requestHandler.Handle(request)); }
public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) { var document = new Use(mapping.DocumentType); method.Frames.Code($"if (string.{nameof(string.IsNullOrEmpty)}({{0}}.{mapping.IdMember.Name})) _setter({{0}}, \"{_mapping.Alias}\" + \"/\" + {{1}}.Sequences.SequenceFor({{2}}).NextLong());", document, Use.Type <IMartenDatabase>(), mapping.DocumentType); method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); }
public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) { var document = new Use(mapping.DocumentType); method.Frames.Code($"if (string.IsNullOrEmpty({{0}}.{mapping.IdMember.Name})) throw new InvalidOperationException(\"Id/id values cannot be null or empty\");", document); method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); }
public override int GetHashCode() { int hash = 1; if (Use.Length != 0) { hash ^= Use.GetHashCode(); } if (Short.Length != 0) { hash ^= Short.GetHashCode(); } if (Long.Length != 0) { hash ^= Long.GetHashCode(); } if (Example.Length != 0) { hash ^= Example.GetHashCode(); } if (Deprecated.Length != 0) { hash ^= Deprecated.GetHashCode(); } if (Hidden != false) { hash ^= Hidden.GetHashCode(); } return(hash); }
public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) { var document = new Use(mapping.DocumentType); method.Frames.Code($"if ({{0}}.{mapping.IdMember.Name} == Guid.Empty) _setter({{0}}, {typeof(Guid).FullNameInCode()}.NewGuid());", document); method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); }
//Создать очередь private int Create() { int k = 9; string[] createMenu = { "Создать очередь с фиксированным объемом (заполнится автоматически)", "Создать очередь с заданным объемом (заполнится автоматически)", "Создать очередь (скопировать из существующей)", "Назад" }; while (true) { int sw = Use.Menu(0, "Выберите действие:", createMenu); switch (sw) { case 1: CreateFixCapacity(); return(0); case 2: CreateFromCapacity(); return(0); case 3: CreateFromReady(); return(0); case 4: return(k); } } }
public void Launch_CalledWith100and100_PositionatesTheWuindow() { Do.Launch(TestData.ApplicationPath).And.Wait(1000); var mainWindow = WindowFinder.Search(Use.AutomationId(TestData.MainWindowAutomationId)); mainWindow.CloseButton.Unsafe.Click(); }
public Item(Use useItem, ItemType type, Texture2D texture, string description, string name) : base() { if (type != ItemType.misc) { this.Colour = new Color(Globals.Randomizer.Next(50, 255), Globals.Randomizer.Next(50, 255), Globals.Randomizer.Next(50, 255)); } this.Depth = 0.1f; this.UseItem = useItem; this.Type = type; this.Texture = texture; Description = description; this.NumberOfItems = 1; this.Name = name; this.ItemLevel = 0; }
protected void btnAccept_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtUsername.Text)) { Use u = new Use(); if (!string.IsNullOrEmpty(Request.QueryString["id"])) { u.UserId = Convert.ToInt32(Request.QueryString["id"].ToString()); } else { u.UserId = 0; } u.UserFname = txtFirstname.Text; u.UserLname = txtSecondname.Text; u.UserAdd1 = txtAddress1.Text; u.UserAdd2 = txtAddress2.Text; u.UserCity = txtCity.Text; u.StateID = DdlState.SelectedIndex; // Double check this u.UserZip = txtZip.Text; u.UserName = txtUsername.Text; u.UserPassword = txtPassword.Text; u.UserPassword = txtConfirmPass.Text; u.UserEmail = txtEmail.Text; u.UserEmail = txtConfirmEmail.Text; u.UserPhone = txtPhone.Text; u.UserRole = "User"; u.Active = Convert.ToBoolean(rblIsActive.SelectedValue.ToString()); if (Use.Save(u)) { Response.Redirect("~/Users.aspx"); } else { lblError.Text = "Error saving record."; } } }
public static bool Save(Use c) { bool b = false; //connection object - ConfigurationManager namespace allows for runtime //access to web.config setting, specifically connection strings and key values SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString); //command object is for direct interface with database //this constructor uses 2 arguments, first is name of stored procedure, //2nd is connection object SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; if (c.UserId > 0) { cmd.CommandText = "spUpdateUser"; cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = c.UserId; } else { cmd.CommandText = "spInsertUser"; } //Create datatable to hold result set DataTable dt = new DataTable(); // Mark the Command as a Stored Procedure //command type is an enumeration: Stored procedure, text(embedded SQL) or table direct cmd.CommandType = CommandType.StoredProcedure; // Add Parameters to Stored Procedure cmd.Parameters.Add("@UserFname", SqlDbType.VarChar).Value = c.UserFname; cmd.Parameters.Add("@UserLname", SqlDbType.VarChar).Value = c.UserLname; cmd.Parameters.Add("@UserAdd1", SqlDbType.VarChar).Value = c.UserAdd1; cmd.Parameters.Add("@UserAdd2", SqlDbType.VarChar).Value = c.UserAdd2; cmd.Parameters.Add("@UserCity", SqlDbType.VarChar).Value = c.UserCity; cmd.Parameters.Add("@StateID", SqlDbType.Int).Value = c.StateID; //Dooble check this cmd.Parameters.Add("@UserZip", SqlDbType.VarChar).Value = c.UserZip; cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = c.UserName; cmd.Parameters.Add("@UserPassword", SqlDbType.VarChar).Value = c.UserPassword; cmd.Parameters.Add("@UserEmail", SqlDbType.VarChar).Value = c.UserEmail; cmd.Parameters.Add("@UserPhone", SqlDbType.VarChar).Value = c.UserPhone; cmd.Parameters.Add("@UserRole", SqlDbType.VarChar).Value = c.UserRole; cmd.Parameters.Add("@UserIsActive", SqlDbType.Bit).Value = c.Active; // Open the database connection and execute the command try { //opens connection to database, most failures happen here //check connection string for proper settings cn.Open(); //execute cmd.ExecuteNonQuery(); b = true; } catch (Exception exc) { //just put here to make debugging easier, can look at error directly exc.ToString(); b = false; } finally { //must always close connections cn.Close(); } // Return the dataset return b; }
public static Use Fetch(int id) { Use u = new Use(); //connection object - ConfigurationManager namespace allows for runtime //access to web.config setting, specifically connection strings and key values SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString); //command object is for direct interface with database //this constructor uses 2 arguments, first is name of stored procedure, //2nd is connection object SqlCommand cmd = new SqlCommand("spGetUserByID", cn); //Create datatable to hold result set DataTable dt = new DataTable(); // Mark the Command as a Stored Procedure //command type is an enumeration: Stored procedure, text(embedded SQL) or table direct cmd.CommandType = CommandType.StoredProcedure; // Add Parameters to Stored Procedure cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = id; // Open the database connection and execute the command try { //opens connection to database, most failures happen here //check connection string for proper settings cn.Open(); //data adapter object is trasport link between data source and //data destination SqlDataAdapter da = new SqlDataAdapter(cmd); //fill method, for multiple tables use dataset da.Fill(dt); } catch (Exception exc) { //just put here to make debugging easier, can look at error directly exc.ToString(); } finally { //must always close connections cn.Close(); } // Return the dataset if (dt.Rows.Count > 0) { u.UserId = Convert.ToInt32(dt.Rows[0]["UserID"].ToString()); u.UserFname = dt.Rows[0]["UserFname"].ToString(); u.UserLname = dt.Rows[0]["UserLname"].ToString(); u.UserAdd1 = dt.Rows[0]["UserAdd1"].ToString(); u.UserAdd2 = dt.Rows[0]["UserAdd2"].ToString(); u.UserCity = dt.Rows[0]["UserCity"].ToString(); u.StateID = Convert.ToInt32(dt.Rows[0]["StateID"].ToString()); u.UserZip = dt.Rows[0]["UserZip"].ToString(); u.UserName = dt.Rows[0]["UserName"].ToString(); u.UserPassword = dt.Rows[0]["UserPassword"].ToString(); u.UserEmail = dt.Rows[0]["UserEmail"].ToString(); u.UserPhone = dt.Rows[0]["UserPhone"].ToString(); u.UserRole = dt.Rows[0]["UserRole"].ToString(); u.Active = Convert.ToBoolean(dt.Rows[0]["UserIsActive"].ToString()); } return u; }
// throws jjtraveler.VisitFailure public void testDefUse() { Def def = new Def(); Use use = new Use(); DefUse du = new DefUse(use, def); du.visit(n0); Assertion.AssertTrue( du.getUnused().contains("noot")); Assertion.AssertTrue( du.getUndefined().contains("mies")); Assertion.AssertEquals(1, du.getUnused().size()); Assertion.AssertEquals(1, du.getUndefined().size()); }