what namespaces used to remove the following errors? - c#

my question is that if the user click on button(which is placed in default.aspx,for example) then the database table is created in database(database is placed in sql express 2005)how can do ?.
I try this task by another method but the following errors are occurred:
1.'system.Web.UI.Page.Server' is a 'property' but is used like a 'type'.
2.The type or namespace name 'Database' could not be found(are you
missing a using directive or an
assembly reference?)
3.The name 'DataType' does not exist in the current context.
4.'System.Web.UI.WebControls.Table' does not contain a definition for
'columns' and no extension method
'columns' accepting a first argument
of type
'System.Web.UI.WebControls.Table' could be found(are you missing a using
directive or an assembly reference.
5.'System.Data.Index' is inaccessible due to its protection
level.
6.'System.Data.Index' does not contain a constructor that takes '2'
arguments.
7.'System.Data.Index' does not contain a definition for
'IndexKeyType' and no extension method
'IndexKeyType' accepting a first
argument of type 'System.Data.Index'
could be found(are you missing a using
directive or an assembly reference?)
8.The name 'IndexKeyType' does not exist in the current context.
9.'System.Data.Index' does not contain a definition
for'IndexedColumns' and no extension
method 'IndexedColumns' accepting a
first argument of type
'System.Data.Index' could be found(are
you missing a using directive or
assembly reference?)
10.The type or namespace name 'Indexedcolumn' could not be found(are
you missing a using directive or an
assembly reference?)
11.'System.Web.UI.WebControls.Table' does not contain a definition for
'Indexes' and no extension method
'Indexes' accepting a first argument
of type
'System.Web.UI.Webcontrols.Table'
could be found(are you missing a using
directive or an assembly reference?)
13.'System.Web.UI.WebControls.Table' does not Contain a definition for
'Create' and no extension method
'Create' accepting a first argument of
type 'Systen.Web.UI.WebControls.Table'
could be found(are you missing a using
directive or an assembly reference?)
The code written in c# behind the button is that:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
//using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
//using System.Data.Odbc;
using Microsoft.SqlServer.Management.Common;
//using ADOX;
//using ADODB;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// Establish the database server
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
SqlConnection connection =
new SqlConnection(connectionString);
Server server =
new Server(new ServerConnection(connection));
// Create table in my personal database
Database db = server.Databases["game"];
// Create new table, called TestTable
Table newTable = new Table(db, "TestTable");
// Add "ID" Column, which will be PK
Column idColumn = new Column(newTable, "ID");
idColumn.DataType = DataType.Int;
idColumn.Nullable = false;
idColumn.Identity = true;
idColumn.IdentitySeed = 1;
idColumn.IdentityIncrement = 1;
// Add "Title" Column
Column titleColumn = new Column(newTable, "Title");
titleColumn.DataType = DataType.VarChar(50);
titleColumn.Nullable = false;
// Add Columns to Table Object
newTable.Columns.Add(idColumn);
newTable.Columns.Add(titleColumn);
// Create a PK Index for the table
Index index = new Index(newTable, "PK_TestTable");
index.IndexKeyType = IndexKeyType.DriPrimaryKey;
// The PK index will consist of 1 column, "ID"
index.IndexedColumns.Add(new IndexedColumn(index, "ID"));
// Add the new index to the table.
newTable.Indexes.Add(index);
// Physically create the table in the database
newTable.Create();
}
}
sir please solve these errors and also give the solution in detail through which i can easily understand.I am very confused in this task please help me.Thank sir

Suggest abandoning your current approach. The problems go beyond namespacing. Suggest taking these steps:
create a brand new test project for the following
determine the SQL statements for
creating a table with all columns
creating the index
execute the SQL statements above using ADO.NET. Suggest a SqlConnection and SqlCommand.
Something like this:
using (var conn = new SqlConnection(connString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = createTableStatement; //CREATE TABLE Foo (ID int);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = createIndexStatement;
cmd.ExecuteNonQuery();
}
}
This will get you started on accomplishing your task. Be sure that any user-entered data aren't simply placed into your strings to create your objects. If so, change the approach to use parameters with your SqlCommand.
Here's an article on Beginner's Guide to Accessing SQL Server Through C#

Related

Do I need to install the same reference/dependencies across multiple namespaces to solve this FileNotFound exception? (C#)

I'm following along with a Tim Corey tutorial on making a Tournament Tracker WinForm app (this one at this point, in case it helps - https://preview.tinyurl.com/yxmyz8h6)
I've gotten to the point where we are starting to hook up the class library to SQL using some NuGet packages - namely Dapper, System.Data.SqlClient & System.Configuration.ConfigurationManager.
So far the project is split across two namespaces, the class library that holds all the models and data access classes (TrackerLibrary) & the form UI (TrackerUI). I was under the impression from the tutorial that these references only need to exist in the class library and not in the UI (as TrackerLibrary is where Tim directed us to add them)
But without them referenced in the TrackerUI - a FileNotFoundException shows up for all three when you run the code. However, that doesn't happen to him in the tutorial.
The SQL connection string is set up in the App.Config file of the TrackerUI and looks like this...
<connectionStrings>
<add name="Tournaments"
connectionString="Server=localhost;Database=TournamentTracker;Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
There is a class in TrackerUI called CreatePrizeForm that has a button click method to validate the form a user completes and then turn that data into a model and pass that model into SQL...
using System;
using System.Windows.Forms;
using TrackerLibrary;
using TrackerLibrary.Models;
namespace TrackerUI
{
public partial class CreatePrizeForm : Form
{
public CreatePrizeForm()
{
InitializeComponent();
}
private void createPrizeButton_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
PrizeModel model = new PrizeModel(
placeNameValue.Text,
placeNumberValue.Text,
prizeAmountValue.Text,
prizePercentageValue.Text);
GlobalConfig.Connection.CreatePrize(model);
placeNameValue.Text = "";
placeNumberValue.Text = "";
prizeAmountValue.Text = "0";
prizePercentageValue.Text = "0";
}
GlobalConfig class handles deciphering whether we are saving to SQL or saving to a Text File as per the imaginary client requirements for the tutorial and grabs the connection string, which looks like this...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using TrackerLibrary.DataAccess;
using System.Data.SqlClient;
using Dapper;
public static class GlobalConfig
{
public static IDataConnection Connection { get; private set; }
public static void InitializeConnections(DatabaseType db)
{
if (db == DatabaseType.Sql)
{
SqlConnector sql = new SqlConnector();
Connection = sql;
}
else if (db == DatabaseType.TextFile)
{
TextConnector text = new TextConnector();
Connection = text;
}
}
public static string CnnString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
The IDataConnection interface looks like this...
using System;
using System.Collections.Generic;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public interface IDataConnection
{
PrizeModel CreatePrize(PrizeModel model);
}
}
And the CreatePrize method looks like this...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new
System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id");
return model;
}
The error occurs when the code reaches here...
GlobalConfig.Connection.CreatePrize(model);
With the following exception...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Data.SqlClient, Version=4.6.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'
When I installed the System.Data.SqlClient NuGet package into the TrackerUI's references - it errors at the same point as before but this time it talks about Dapper...
System.IO.FileNotFoundException: 'Could not load file or assembly 'Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.'
Then if you then install Dapper into TrackerUI references, it gets past the GlobalConfig.Connection.CreatePrize call into SqlConnector.cs and errors on the using (IDbConnection connection = new System.Data.SqlClient.SqlConnection... line below...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id"); //Pulls ID from the p variable that represents the id of the record in the database
return model;
}
With another FileNotFoundException...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'
Adding references within the TrackerUI namespace to Dapper, System.Data.SqlClient and System.Configuration.ConfigurationManager resolves the exceptions and enables the program to write to SQL no problem. I just wanted to clear up whether that was what I needed to do by default or whether I've missed something earlier and the TrackerUI namespace shouldn't feature references to them. Just don't want to get into bad habits.
Sorry if I've missed any important detail - kinda new to this and have tried to be as thorough as possible but let me know if there is anything else I need to provide.
Thank you for your clarification and help in advance!

What reference should I use for 'Data.ValueRange'?

I'm following a guide to write output data from Visual Studio into a google spreadsheet.
At the end of the guide there is a code block that I pasted inside my project:
using OpenQA.Selenium.Support.UI;
using System;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections;
using System.Collections.Generic;
using Google.Apis.Sheets.v4;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Services;
using Newtonsoft.Json;
using WikipediaTests.Foundation_Class;
using System.Web;
using System.Data;
using Google.Apis.Sheets.v4.Data;
namespace AutomationProjects
{
[TestFixture]
public class TestClass : TestFoundation
{
public class SpreadSheetConnector
{
//Codeblock from guide pasted here!
}
[Test]
public void test1()
{
//Test case 1. Do XYZ...
}
}
}
In the code block included in the guide there is a section about creating a list and passing data into it:
// Pass in your data as a list of a list (2-D lists are equivalent to the 2-D spreadsheet structure)
public string UpdateData(List<IList<object>> data)
{
String range = "My Tab Name!A1:Y";
string valueInputOption = "USER_ENTERED";
// The new values to apply to the spreadsheet.
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
var dataValueRange = new Data.ValueRange();
dataValueRange.Range = range;
dataValueRange.Values = data;
updateData.Add(dataValueRange);
Data.BatchUpdateValuesRequest requestBody = new Data.BatchUpdateValuesRequest();
requestBody.ValueInputOption = valueInputOption;
requestBody.Data = updateData;
var request = _sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, _spreadsheetId);
Data.BatchUpdateValuesResponse response = request.Execute();
// Data.BatchUpdateValuesResponse response = await request.ExecuteAsync(); // For async
return JsonConvert.SerializeObject(response);
}
The problem is that I get an error for the 'Data.ValueRange' and the 'Data.BatchUpdateValuesRequest' :
CS0246 The type or namespace name 'Data' could not be found (are you missing a using directive or an assembly reference?)
I tried adding "System.Data" as a assembly reference to my project and then added it at the top (using). But it did not remove the error.
'Data.' seems to belong to "Google.Apis.Sheets.v4" but I have already added that reference as the guide instructed.
The only fix that gets rid of the error is adding Google.Apis.Sheets.v4 before every 'Data.' like this:
List<Google.Apis.Sheets.v4.Data.ValueRange>
But when I run my tests the output does not get exported to my spreadsheet. So I'm assuming this is not the correct solution. And also I'm assuming that the guide should have included this in the code block if it was necessary.
Could there be some other reference about 'Data' I need?
According to the documentation, the ValueRange Class depends of Sheets.v4.Data, so you should add:
using Google.Apis.Sheets.v4.Data;
Also, change:
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
to:
List<ValueRange> updateData = new List<ValueRange>();

How to Debug C# code in visual studio code

I want to debug my c# code in vs code but when I run I encountered some errors .and it needs some references.so I add system.data.sqlclient but again it needs reference for SqlDataAdapter .please help me to solve this problem
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
try
{ DataTable dt = new DataTable();
SqlConnection sqlconn = new SqlConnection(DBsetting.Connstring);
SqlDataAdapter sqlda = new SqlDataAdapter("SelectUserswith", sqlconn);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.AddWithValue("#n", textBox1.Text.Trim());
dt.Clear();
sqlda.Fill(dt);
if (dt.Rows!=null && dt.Rows.Count > 0 && dt.Rows[0]["username"] != null && dt.Rows[0]["Depassword"].ToString() == textBox2.Text.Trim())
{
this.Hide();
MenuFrm f1 = new MenuFrm();
f1.un = dt.Rows[0]["name"].ToString();
f1.uID = dt.Rows[0]["ID"].ToString();
f1.username = dt.Rows[0]["username"].ToString();
f1.Show();
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Error :
file: 'file:///c%3A/Users/JAVAD/Documents/SampleVsCode/Program.cs'
severity: 'Error'
message: 'The type or namespace name 'SqlDataAdapter' could not be found (are you missing a using directive or an assembly reference?)'
at: '13,17'
source: ''
file: 'file:///c%3A/Users/JAVAD/Documents/SampleVsCode/Program.cs'
severity: 'Error'
message: ''DataTable' does not contain a definition for 'Clear' and no extension method 'Clear' accepting a first argument of type 'DataTable' could be found (are you missing a using directive or an assembly reference?)'
at: '16,20'
source: ''
Software :
The using clause makes a reference to the namespace of the classes you are using. You also need to add a reference to the dll that the namespace is defined in.
in solution explorer there is a node under your project called Reference . Right click this ans choose Add from the menu. Find System.Data and include that.
If you refer to the MSDN documentation at https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx
It tells you the namespace and dll you need.
Namespace: System.Data.SqlClient
Assembly: System.Data (in System.Data.dll)

Does not contain a definition for 'Show' and no extension method 'Show' error

I am trying to show an instance of PluginManagerView with the below code.
This XAML file is in the same namespace, same project. But I got an error at the line of mainwindow.Show(); saying that
Error 1 'PluginManager.PluginManagerView' does not contain a definition for 'Show' and no extension method 'Show' accepting a first argument of type 'PluginManager.PluginManagerView' could be found (are you missing a using directive or an assembly reference?) Blah procedyre .cs 30 24 PluginManager
Can anyone tell me about what the problem is? And why doesn't it throw the error for the prior usages of MainWindow?
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.ComponentModel.Composition.Hosting;
namespace PluginManager
{
public class PublicProcedures : Application
{
public static void ShowPlugins()
{
var mainwindow = new PluginManagerView();
//An aggregate catalog that combines multiple catalogs
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
//catalog.Catalogs.Add(new AssemblyCatalog(this.GetType().Assembly));
catalog.Catalogs.Add(new DirectoryCatalog("./Plugins/"));
var container = new CompositionContainer(catalog);
var modules = container.GetExportedValues<IPlugin>();
mainwindow.DataContext = modules;
mainwindow.Show();
}
}
}
In order to call Window.Show (which i guess is what you want to do), PluginManagerView would have to be derived from class Window, and its XAML would have to look somehow like this:
<Window x:Class="PluginManager.PluginManagerView" ...>
...
</Window>
It is complaining that whatever PluginManagerView is, it doesn't have a Show method (which you're trying to call in an instance of PluginManagerView called "mainwindow").

Entity Error in GDataDB example

Im getting the error "the type or namespace name 'Entity' could not be found" from the following code snippet.
So ive added the reference "System.Data.Entity" but its still not working...
Why is that?
Error 1 The type or namespace name 'Entity' could not be found (are you missing a using directive or an assembly reference?)...
using System;
using System.Linq;
using GDataDB;
using GDataDB.Linq;
using System.Data.Entity;
....
Console.WriteLine("Connecting");
var client = new DatabaseClient("you#gmail.com", "password");
const string dbName = "testing";
Console.WriteLine("Opening or creating database");
var db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName);
const string tableName = "testtable";
Console.WriteLine("Opening or creating table");
var t = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName);
Console.WriteLine("Feed url for this table is '{0}'", t.GetFeedUrl());
var all = t.FindAll();
Console.WriteLine("{0} elements", all.Count);
....
There is no using System.Data.Entity; in the GDataDB sample app, and never has been, so either you or some automated tool added it.
So simply remove it.
If you're missing the Entity type, make sure you get the whole sample project and not just Program.cs
GDataDB has no relationship to EF or LINQ-to-SQL at all.

Categories

Resources