XNA foreach statement error - foreach

I keep getting this error in the code below. can somebody tell me what I did Wrong.
foreach statement cannot operate on variables of type 'method group' because 'method group' does not contain a public definition for
private void updateVelocity(KeyboardState keyboardState)
{
var keysdictionay = new Dictionary<Keys, Vector2>
{
{Keys.Left, new Vector2(-1, 0)},
{Keys.Right, new Vector2(1, 0)},
{Keys.Up, new Vector2(0, -1)},
{Keys.Down, new Vector2(0, 1)}
};
var velocity = Vector2.Zero;
foreach (var keypress in keyboardState.GetPressedKeys)
{
velocity += keysdictionay[keypress];
}
Velocity = velocity * shipspeed;
}
public Vector2 Velocity { get; set; }
float shipspeed = 300.0f;
}
}

GetPressedKeys is a method. use () on it
foreach (var keypress in keyboardState.GetPressedKeys())

Related

pie doesn't display

I am trying to create a pie chart using SyncFusion bind in SQL Server in ASP.NET MVC, however the chart doesn't display, no error message found when I rebuild the code and it runs but no chart display. I wondered what could the cause of the chart doesn't load
I tried this code to connect the Syncfusion pie chart to SQL Server
string command2 = "SELECT * FROM [myTable] WHERE Item_ID < 10";
SqlCommand cmd1 = new SqlCommand(command2, con);
adapter.SelectCommand = cmd1;
adapter.Fill(dataset);
for (var i = 0; i < dataset.Tables[0].Rows.Count; i++)
{
int x1 = (int)Convert.ToInt32(dataset.Tables[0].Rows[i]["this.Item_ID"]);
int y1 = (int)Convert.ToInt32(dataset.Tables[0].Rows[i]["Item_Score"]);
data.Add(new ChartSqlData(x1, y1));
}
CSHTML view:
#(Html.EJS().AccumulationChart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.AccumulationType.Pie)
.XName("Item_ID")
.YName("Item_Score")
.Name("Item_ID")
.Explode(true)
.DataLabel(dl => dl.Visible(true).Name("Item_ID").Position(Syncfusion.EJ2.Charts.AccumulationLabelPosition.Outside).ConnectorStyle(cs => cs.Type(Syncfusion.EJ2.Charts.ConnectorType.Line).Length("5 %")).Font(ft => ft.Size("14px")))
.Animation(animate => animate.Enable(true))
.Radius("70%")
.StartAngle(0)
.EndAngle(360)
.InnerRadius("0%")
.GroupTo("9")
.GroupMode(Syncfusion.EJ2.Charts.GroupModes.Point)
.DataSource(ViewBag.dataSource).Add();
})
Controller:
List<ChartSqlData> data = new List<ChartSqlData>();
string connectionString = null;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet dataset = new DataSet();
connectionString = #"Data Source=LAPTOP-V3QJAMBF\SQLEXPRESS;Initial Catalog=My_Database;Integrated Security=True;";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string command2 = "SELECT * FROM [myTable] WHERE Item_ID < 10";
SqlCommand cmd1 = new SqlCommand(command2, con);
adapter.SelectCommand = cmd1;
adapter.Fill(dataset);
for (var i = 0; i < dataset.Tables[0].Rows.Count; i++)
{
int x1 = (int)Convert.ToInt32(dataset.Tables[0].Rows[i]["this.Item_ID"]);
int y1 = (int)Convert.ToInt32(dataset.Tables[0].Rows[i]["Item_Score"]);
data.Add(new ChartSqlData(x1, y1));
}
ViewBag.dataSource = data;
return View();
[Serializable]
public class ChartSqlData
{
public ChartSqlData(int xvalue, int yvalue1)
{
this.Item_ID = xvalue;
this.Item_Score = yvalue1;
}
public int Item_ID { get; set; }
public int Item_Score { get; set; }
}
This is because of Render method is not yet called at an end of control creation. I have added that and prepared sample based on your need. Please check the below snippet and sample.
#(Html.EJS().AccumulationChart("container").Render())
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/PieDB1343192459.zip

How to refactor the connectionString in my Entity Framework & ASP.NET MVC project?

I have a large number of stored procedures to work with and I have to work with Entity Framework.
I got for example this controller where I'm just calling the database to show my table:
public class CarguioController : Controller
{
public ActionResult Index(int? page)
{
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
// establece conneciĆ³n
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#MODO";
param1.SqlDbType = SqlDbType.Int;
param1.Value = 2;
SqlCommand cmdProcedure = new SqlCommand(#"Almacen.[PRC_Carguio]", conn);
cmdProcedure.Parameters.Add(param1);
conn.Open();
cmdProcedure.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmdProcedure.ExecuteReader();
List<CarguioViewModel> lst = new List<CarguioViewModel>();
int pageNumber = page ?? 1;
int pageSize = 8;
if (dr.HasRows)
{
while (dr.Read())
{
lst.Add(new CarguioViewModel
{
Carguio_ID = dr.GetInt32(0),
Vehiculos_ID = dr.GetInt32(1),
ManifiestoCarga_ID = dr.GetInt32(2),
Guia_ID = dr.GetInt32(3),
Programaciones_ID = dr.GetInt32(4),
Numero = dr.GetInt32(5),
NroMobil = dr.GetString(6),
Fecha = dr.GetDateTime(7),
Usuarios_ID = dr.GetInt32(8),
Sucursales_IS = dr.GetInt32(9)
});
//display retrieved record
}
return View(lst.ToPagedList(pageNumber, pageSize));
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
conn.Close();
}
return View();
}
}
As you can see, I have to connect with the SQL Server database many times. Maybe you have done a similar job with ASP.NET MVC projects or have any idea to refactor my code?
I have more than 30 tables and everyone has more a Crud and other functions.
I've been searching for this but there is just the same example.
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
You can get create in General Utility class to read the connection, so that It is stay in one place in the code and read connection value from the Genral Utility class wherever you need it.
void Main()
{
string cn = GeneralUtility.getConnectionString();
}
public class GeneralUtility
{
public static string getConnectionString()
{
string cs = "";
try
{
cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
catch (Exception ex)
{
throw new Exception("Connection String Error " + ex.Message.ToString());
}
return cs;
}
}
I added a new element called ADO.Net Entity Data Model, where I retrieve all my Stored Procedures, It is helpful
I added a new element called ADO.Net Entity Data Model
Well, now my code is shorter than before:
public ActionResult Index(int? page)
{
List<CarguioModel> lst = new List<CarguioModel>();
int pageNumber = page ?? 1;
int pageSize = 8;
using (MarviBKPEntities prcAlm = new MarviBKPEntities())
{
List<PRC_Carguio_Result> prc = prcAlm.PRC_Carguio(2, null, null, null, null, null, null, null, null, null, null).ToList();
return View(prc.ToPagedList(pageNumber, pageSize));
}
return View();
}
Whta do you think? Could it cause some bad performance?

Collision Detection, Player with tiles of the map

How do I to make a collision with a tile from the map with my player?
Animation class:
public class Animation
{
public float speed = 2.5f;
protected string currentAnimatie;
public Texture2D sTexture;
public Vector2 sPosition;
private int FrameIndex;
private double TimeElapse;
private double TimeToUpdate;
public Vector2 sDirection = Vector2.Zero;
public Rectangle BoxRondCharachter
{
get
{
return new Rectangle((int)sPosition.X, (int)sPosition.Y, 50, 41);
}
}
public int FramesPerSec
{
set { TimeToUpdate = (1f / value); }
}
public Animation(Vector2 pos)
{
sPosition = pos;
}
public void Update(GameTime gametime)
{
TimeElapse += gametime.ElapsedGameTime.TotalSeconds;
if (TimeElapse > TimeToUpdate)
{
TimeElapse -= TimeToUpdate;
if (FrameIndex < sAnimatie[currentAnimatie].Length - 1)
{
FrameIndex++;
}
else
{
FrameIndex = 0;
}
TimeElapse = 0;
}
sPosition += sDirection;
sDirection = Vector2.Zero;
}
public void AddAnimatie(int frames, double yPos, int xStart, string naam, int width, int height, Vector2 offset)
{
Rectangle[] Rectangles = new Rectangle[frames];
///neemt de spritesheet en het verdeelt zich
for (int i = 0; i < frames; i++)
{
Rectangles[i] = new Rectangle((i + xStart) * width, (int)yPos, width, height);
}
sAnimatie.Add(naam, Rectangles);
}
public void Draw(SpriteBatch sprite)
{
sprite.Draw(sTexture, sPosition, sAnimatie[currentAnimatie [FrameIndex], Color.White);
}
public void AnimatieAfspelen(string animatieNaam)
{
if (currentAnimatie != animatieNaam)
{
currentAnimatie = animatieNaam;
FrameIndex = 0;
}
}
public void LaadContent(ContentManager content)
{
sTexture = content.Load<Texture2D>("char");
}
}
MapEngine Class:
class MapEngine
{
private List<CollisionTiles> collisionTiles = new List<CollisionTiles>();
public List<CollisionTiles> CollisionTiles
{
get { return collisionTiles; }
}
private int width, height;
public int Width
{
get { return width; }
}
public int Height
{
get { return height; }
}
public MapEngine()
{
}
public void Generate(int[,] map, int size)
{
for (int x = 0; x < map.GetLength(1); x++)
{
for (int y = 0; y < map.GetLength(0); y++)
{
int number = map[y, x];
if (number > 0)
{
collisionTiles.Add(new CollisionTiles(number, new Rectangle(x * size, y * size, size, size)));
width = (x + 1) * size;
height = (y + 1) * size;
}
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (CollisionTiles tile in collisionTiles)
{
tile.Draw(spriteBatch);
}
}
}
Map class:
class Map : MapEngine
{
public void ShowMap(ContentManager Content)
{
Tiles.Content = Content;
Generate(new int[,]{
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
{2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,},
{2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2,},
{2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2,},
{2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2,},
{2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2,},
{2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,},
{2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,}
}, 74);
}
}
Hero class:
public class Hero
{
private Vector2 position = new Vector2(54, 485);
public Vector2 Position
{
get { return position; }
}
public int Width { get; set; }
public int Height { get; set; }
private Animation _animation;
private Inputs inputH = new Inputs();
public bool LinkseStand = false;
private Rectangle collisionRectangle;
public Rectangle CollisionRectangle
{
get => collisionRectangle;
set => collisionRectangle = value;
}
public Hero()
{
_animation = new Animation(position);
_animation.AddAnimatie(4, 0, 0, "RechteIdle", 50, 35, new Vector2(0, 0));
_animation.AddAnimatie(4, 34, 0, "LinkseIdle", 50, 35, new Vector2(0, 0));
_animation.AddAnimatie(6, 72, 0, "Right", 50, 34, new Vector2(0, 0));
_animation.AddAnimatie(6, 107, 0, "Left", 50, 40, new Vector2(0, 0));
_animation.AddAnimatie(9, 144, 0, "Jump", 46, 41, new Vector2(0, 0));
_animation.AddAnimatie(4, 220, 0, "Crouch", 50, 32, new Vector2(0, 0));
_animation.AddAnimatie(7, 255, 0, "FirstAttack", 50, 45, new Vector2(0, 0));
_animation.AddAnimatie(14, 300, 0, "ComboAttack", 50, 41, new Vector2(0, 0));
_animation.AddAnimatie(5, 300, 0, "Dood", 50, 41, new Vector2(0, 0));
_animation.AnimatieAfspelen("RechteIdle");
_animation.FramesPerSec = 8;
}
public void Draw(SpriteBatch spritebatch)
{
_animation.Draw(spritebatch);
}
public void laadContent(ContentManager content)
{
_animation.LaadContent(content);
}
public void Update(GameTime gameTime)
{
_animation.Update(gameTime);
position += _animation.sDirection;
CollisionRectangle = new Rectangle((int)_animation.sPosition.X, (int)_animation.sPosition.Y, 50, 41);
inputH.update();
Move(gameTime);
}
private void Move(GameTime gameTime)
{
if (inputH.Right)
{
_animation.AnimatieAfspelen("Right");
_animation.sDirection.X = _animation.speed;
LinkseStand = false;
}
else if (inputH.Left)
{
_animation.AnimatieAfspelen("Left");
_animation.sDirection.X -= _animation.speed;
LinkseStand = true;
}
else if (inputH.Up)
{
_animation.AnimatieAfspelen("Jump");
_animation.sDirection.Y -= _animation.speed;
}
else if (inputH.NormalAttack)
{
_animation.AnimatieAfspelen("FirstAttack");
}
else if (inputH.ComboAttack)
{
_animation.AnimatieAfspelen("ComboAttack");
}
else
{
if (LinkseStand == true)
_animation.AnimatieAfspelen("LinkseIdle");
else
_animation.AnimatieAfspelen("RechteIdle");
}
}
}
Collision tile class:
class CollisionTiles : Tiles
{
public CollisionTiles(int i, Rectangle newRect)
{
texture = Content.Load<Texture2D>("Tile" + i); //loads the tile (tile1, tile2)
Rectangle = newRect;
}
}
Game1 class:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D background;
Vector2 backPos;
Animation _ani;
Hero _hero;
Map map;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1000; // set this value to the desired width of your window
graphics.PreferredBackBufferHeight = 590; // set this value to the desired height of your window
graphics.ApplyChanges();
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
map = new Map();
_hero = new Hero();
_ani = new Animation(_hero.Position);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
background = Content.Load<Texture2D>("background1");
backPos = new Vector2(0, 0);
map.ShowMap(Content);
//_heroTexture = Content.Load<Texture2D>("idleStand");
_hero.laadContent(Content);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
_hero.Update(gameTime);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Cyan);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(background, backPos, Color.White);
map.Draw(spriteBatch);
_hero.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
You can pass the Map instance to the Hero in the Update method in Game1:
_hero.Update(gameTime, map);
And use that to loop through the map.CollisionTiles list checking for overlaps in the Hero class:
public void Update(GameTime gameTime, Map map)
{
_animation.Update(gameTime);
position += _animation.sDirection;
CollisionRectangle = new Rectangle((int)_animation.sPosition.X, (int)_animation.sPosition.Y, 50, 41);
// Check for collision with any of the CollisionTiles:
foreach(var item in map.CollisionTiles)
if(item.Rectangle.Intersects(CollisionRectangle))
// ^^^^^^^^^ needs to be public in the tile class.
{
position -= _animation.sDirection; // Collided with a tile undo move
break; //prevent moving backwards if colliding with more than one tile
}
inputH.update();
Move(gameTime);
}
In this code, the Hero is prevented from moving onto any CollisionTile.

Loop optimization (Multi level Menu) ASP.NET

I'm trying create a function to generate HTML file for multi-language menu. The code can work but only problem is its taking too long to compile. The flow is, this function will be called in the Global.asax file (process before start the program)
I suspect it caused by the looping process. So please advice me about the optimization. Thank you in advance. Here is the code.
public static void GenerateMenu(string strPath)
{
string[] tempCateHTML = new string[] { "_temp_menu_en.cshtml", "_temp_menu_bm.cshtml", "_temp_menu_ch.cshtml" }; //temporary file names
string[] cateHTML = new string[] { "_menu_en.cshtml", "_menu_bm.cshtml", "_menu_ch.cshtml" };
for (int i = 0; i < 3; i++)
{
using (EFContext ctx = new EFContext())
{
List<int> parentId = new List<int>();
List<Category> parentCategory = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = 0").ToList();
StringWriter sWriter = new StringWriter();
using (HtmlTextWriter wt = new HtmlTextWriter(sWriter))
{
foreach (Category cate in parentCategory)
{
string[] columnParent = new string[] { cate.Category_Name, cate.Category_NameBM, cate.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li); //<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A); //<a>
wt.Write(columnParent[i]);
wt.RenderEndTag();//</a>
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
List<Category> childCategoryL1 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", cate.CategoryID).ToList();
foreach (Category root in childCategoryL1)
{
string[] columnChild1 = new string[] { root.Category_Name, root.Category_NameBM, root.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild1[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL2 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", root.CategoryID).ToList();
if (childCategoryL2.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child1 in childCategoryL2)
{
string[] columnChild2 = new string[] { child1.Category_Name, child1.Category_NameBM, child1.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild2[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL3 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", child1.CategoryID).ToList();
if (childCategoryL3.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child2 in childCategoryL3)
{
string[] columnChild3 = new string[] { child2.Category_Name, child2.Category_NameBM, child2.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild3[i]);
wt.RenderEndTag();//</a>
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
wt.RenderEndTag();//</li>
}
}
string menuHTML = sWriter.ToString();
string filePath = Path.Combine(strPath, #"Views\Shared\CacheData\CateMenu\");
new FileInfo(filePath).Directory.Create(); //create new folder
var menuPath = String.Format("{0}{1}", filePath, tempCateHTML[i]); //create multiple HTML files for multiple language
using (FileStream fs = new FileStream(menuPath, FileMode.Append, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(menuHTML);
sw.Flush();
sw.Close();
fs.Close();
}
if (!File.Exists(filePath + cateHTML[i]))
{
using (File.Create(filePath + cateHTML[i]))
{
//create dummy file if the file doesnt exists
}
}
File.Replace(menuPath, filePath + cateHTML[i], filePath + cateHTML[i] + ".bac");
}
}
}
it's a long process. So really Thank you for the time
Actuall I've already found the solution for my problem. The solution was built tree menu based on this method. Thank you for the help.

How to return a DataSet to a View

I am sending a standard Sql select statement to my Sql box via the SqlDataAdapter, then populating a DataSet object.
I can access the rows in the resulting DataSet, but how can I convert the DataSet into a List which can be returned to the MVC View. i.e. I'm assuming a List object is the best way to handle this.
Here's my controller c# code:
public class QAController : Controller
{
private readonly static string connString = ConfigurationManager.ConnectionStrings["RegrDBConnection"].ToString();
private readonly static SqlConnection sqlConn = new SqlConnection(connString);
private readonly static SqlCommand sqlComm = new SqlCommand();
public ActionResult Index()
{
DbRegressionExec();
return View();
}
public static void DbRegressionExec()
{
// SELECT TABLE CONTENTS FROM SQL !!
RegressDB_TableList regresDB = new RegressDB_TableList();
string sqlStr = "select * from [RegressionResults].[dbo].[Diff_MasterList] order by TableName";
// POPULATE DATASET OBJECT
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, sqlConn);
da.SelectCommand.CommandType = CommandType.Text;
sqlConn.Open();
try
{
da.Fill(ds, "RegresDB");
}
catch (Exception e)
{
throw;
}
finally
{
sqlConn.Close();
}
// I can iterate thru rows here, but HOW DO CONVERT TO A LIST OBJECT ????
int numRows = ds.Tables["RegresDB"].Rows.Count;
for (int i = 0; i < numRows; i++)
{
string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
}
//List<RegressDB_TableList> masterList = regresDB.RegresTableList.ToList(); //not working !!
//var masterList = regresDB.TableName.ToList(); //
}
}
and a simple class I may need to make this happen:
namespace RegressionMvc.Models
{
public class RegresDB_TableName
{
public string TableName { get; set; }
}
public class RegressDB_TableList
{
public List<RegresDB_TableName> RegresTableList { get; set; }
}
}
In the end, I'm trying to figure out the best way to handle DataSet results from Sql Server and how to make them back to an MVC View.
I can probably go with jQuery and Json, meaning just convert the data fields to Json and return to JQuery, but I'm sure there are several ways to handle Sql based result sets.
Thanks in advance for your advice....
Best,
Bob
In your controller put the code like this
[HttpGet]
public ActionResult View(Modelclass viewmodel)
{
List<Modelclass> employees = new List<Modelclass>();
DataSet ds = viewmodel.GetAllAuthors();
var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Modelclass{
AuthorId = dataRow.Field<int>("AuthorId"),
Fname = dataRow.Field<string>("FName"),
Lname = dataRow.Field<string>("Lname")
});
var list = empList.ToList();
return View(list);
}
And in view
#{
var gd = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
gd.Pager(WebGridPagerModes.NextPrevious);}
#gd.GetHtml(tableStyle: "table",
columns: gd.Columns(
gd.Column("AuthorId", "AuthorId"),
gd.Column("Fname", " Fname"),
gd.Column("Lname", "Lname", style: "description")
))
Short answer
Directly answering your question:
var tableList = new List<RegresDB_TableName>();
int numRows = ds.Tables["RegresDB"].Rows.Count;
for (int i = 0; i < numRows; i++)
{
string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
tableList.Add(new RegresDB_TableName() { TableName = tblName };
}
return View(tableList);
Long answer (that's actually shorter)
Try out dapper-dot-net.
Your code could change to something like:
string sqlStr = "SELECT * FROM [RegressionResults].[dbo].[Diff_MasterList] ORDER BY TableName";
return sqlConn.Query<RegresDB_TableName>(sqlStr);
If you're stuck with using DAO, I would suggest not using a DataSet and instead use a strongly typed class with the speed of SqlDataReader.GetValues() method. It's more work, but it has to be done somewhere if you want strongly typed classes which I would highly recommend.
public class Person
{
public Person(Object[] values]
{
this.FirstName = (string)values[0];
this.LastName = (string)values[1];
this.Birthday = (DateTime)values[2];
this.HasFavoriteColor = (bool)values[3];
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
public DateTime Birthday { get; private set; }
public bool HasFavoriteColor { get; private set; }
}
public static void DbRegressionExec()
{
List<Person> viewModel = new List<Person>();
// SELECT TABLE CONTENTS FROM SQL !!
RegressDB_TableList regresDB = new RegressDB_TableList();
string sqlStr = "select
FirstName
,LastName
,Birthday
,HasFavoriteColor
from [RegressionResults].[dbo].[Diff_MasterList]
order by TableName";
// POPULATE VIEWMODEL OBJECT
sqlConn.Open();
try
{
using (SqlCommand com = new SqlCommand(sqlStr, sqlConn))
{
using (SqlDbReader reader = com.ExecuteReader())
{
while(reader.Read())
{
viewModel.Add(new Person(com.GetValues()));
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
sqlConn.Close();
}
return this.View(viewModel);
}
Controller code
//pQ is your query you have created
//P4DAL is the key name for connection string
DataSet ds = pQ.Execute(System.Configuration.ConfigurationManager.ConnectionStrings["Platform4"].ConnectionString);
//ds will be used below
//create your own view model according to what you want in your view
//VMData is my view model
var _buildList = new List<VMData>();
{
foreach (DataRow _row in ds.Tables[0].Rows)
{
_buildList.Add(new VMData
{
//chose what you want from the dataset results and assign it your view model fields
clientID = Convert.ToInt16(_row[1]),
ClientName = _row[3].ToString(),
clientPhone = _row[4].ToString(),
bcName = _row[8].ToString(),
cityName = _row[5].ToString(),
provName = _row[6].ToString(),
});
}
}
//you will use this in your view
ViewData["MyData"] = _buildList;
View
#if (ViewData["MyData"] != null)
{
var data = (List<VMData>)ViewData["MyData"];
<div class="table-responsive">
<table class="display table" id="Results">
<thead>
<tr>
<td>Name</td>
<td>Telephone</td>
<td>Category </td>
<td>City </td>
<td>Province </td>
</tr>
</thead>
<tbody>
#foreach (var item in data)
{
<tr>
<td>#Html.ActionLink(item.ClientName, "_Display", new { id = item.clientID }, new { target = "_blank" })</td>
<td>#item.clientPhone</td>
<td>#item.bcName</td>
<td>#item.cityName</td>
<td>#item.provName</td>
</tr>
}
</tbody>
</table>
</div>
}

Resources