How to check if certain data is already in the database? - c#

Im doing a Project for my internship right now and I want to know how to get data from html and from the database and compare if the html data already exists in the database.
I have tried to run it but now I always get the localhost not found error.
HTML
Edit: The Context and the Database are working fine.
#{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Starter</title>
<style>
p {
margin-top: 30%;
margin-left: 20%;
margin-right: 20%;
font-family: Arial;
font-size: 25px;
text-align: center;
}
#Code {
border: 2px solid black;
}
</style>
</head>
<body>
<h1>249765876358312345655</h1>
<p>
Eingabe des Maschinen Codes:
<br />
<!-- Here is the important stuff for this aka HTML data-->
<input id="Code"
name="code"
pattern=""
size="30"
spellcheck="false"
title="Maschine Code"
value="">
</p>
<script>
var x = document.getElementById("Code");
x.addEventListener('input', function (event) {
x = document.getElementById("Code").value;
let vars = x;
let digits = vars.match(/^\d{13}(\d{6})\d{2}$/)[1];
let stringDigits = digits.toString();
if (stringDigits.length == 6 && vars.length == 21) {
window.location.href = '/home/Kontrolle';
document.getElementById("Code").innerHTML = "";
localStorage.setItem("Code_Kurz", stringDigits);
}
}
);
</script>
</body>
</html>
Controller
namespace Qualitätskontrolle.Controllers
{
public class HomeController : Controller
{
Boolean newID;
[HttpPost]
public IActionResult StartPage(string Code)
{
try
{
ViewData["Code"] = Code;
ApplicationDbContext dbContext = new ApplicationDbContext();
var Ergebnisse = dbContext.Result.ToArray();
for (int i = 0; i < Ergebnisse.Length; i++)
{
if (!Ergebnisse[i].Equals(ViewData["Code"]))
{
//Create New Page
newID = true;
}
else
{
newID = false;
}
return View();
}
}
catch
{
return View();
}
return View();
}
}
The result should be that a new site opens depending on wheter its a new Code or an old one.

Can you please check with this approach?
Considered that Code is the name of the column of the Result table in with the value of Code is getting saved.
var Ergebnisse = dbContext.Result.FirstOrDefault(x => x["Code"] == ViewData["Code"].ToString());
if(Ergebnisse != null)
{
// Means the item with same code exist
}
else
{
// Means the item with same code is not exist
}
So, the above code will check for the row having a value is code column which is equal to the value that we are giving[ViewData["Code"]], if no such value is found, then null will be assigned to Ergebnisse. A simple if..else can be used to check the value

Related

Can't interact Selenium Chromedriver with Chrome extension made TextArea

I have a GoogleMeets extension that will help with attendance of persons inside the meet. (It's Google Meet Attendance - https://github.com/al-caughey/Google-Meet-Attendance)
After I open the webpage with selenium webdriver and interact with a icon element to show the textarea when I try to interact with this textarea it I get Exception: Element Not Interactable or Cannot set property of 'innerText' of null when using IJavaScriptExecutor
NOTE
Functions names are different because i made a wrapper class around the IWebDriver Object
The HTML code of page and TextArea
The HTML code of page and TextArea:
<!DOCTYPE html>
<html lang="ro" dir="ltr"> >
<head>...</head>
<body jscontroller="pjice" jsaction="rcuQ6b: npT2md; click:FAbpgf; auxclick:
Abpgf; mousedown:.CLIENT; keydown:.CLIENT;UjQMac:.CLIENT;WINJic:.CLIENT;PDJFbb:.C
LIENT; AbmZie:.CLIENT; keyup:.CLIENT; keypress:.CLIENT;nHjqDd:.CLIENT; Lhiqec:.CLIE
NT;VSCbUd:.CLIENT;GvneHb:.CLIENT;qakode:.CLIENT" class="EI1Dfe">
<script aria-hidden="true" nonce>
window.wiz_progress && window.wiz_progress();
</script> >
<div class="MCCOAC IqBFM ecJEib EwZcud cjGgHb d8Etdd LcUz9d" id="yDmHºd" style="bottom: auto; right: auto; width: 1318px; height: 870px;">...</div>
<div class="MhØNND Mp270b xbg16e mistle" jsaction="click:.CLIENT" style="vi
sibility: visible;">...</div>
<div aria-live="polite" aria-atomic="true" style="position: absolute; top:
-1000px; height: 1px; overflow: hidden;"></div>
<div id="gma-attendance-fields" data-generate-files="both" class data-auto- add="true">
<div id="gma-class-list-div"> >
<p id="gma-class-list-header" class="gma-header" style="display: block;
">...</p> >
<p id="p-attendance-summary" title="Not Monitoring Attendance!">.</p>
<textarea id="class-notes" title="If you want to add any notes related
to this class..." placeholder="Enter any notes specific to this clas
S." X/textarea> >
<p id="invited-list-help" class>...</p>
<textarea id="invited-list" title="Pick, paste or type your class list
into this field" placeholder="Your class list goes here.
Click the blue question mark below for help." classx</textarea> == $0 >
<div id="ema-class-list-buttons" class></div>
CODE
public void start_bot()
{
this.setDriverTimeout(60);
if (this.driver.WindowHandles.Count > 1)
{
this.driver.SwitchTo().Window(this.driver.WindowHandles[1]);
}
try
{
IWebElement classroom = this.findElementByXPath("//*[#id='class-list-edit']");
//classroom = this.findElementByXPath("/html/body/div[3]/div[1]/p[1]/select");
while (!classroom.Enabled && !classroom.Displayed)
{
classroom = this.findElementByXPath("//*[#id='class-list-edit']");
}
classroom.Click();
Thread.Sleep(5000);
classroom = this.findElementByClassName("being-editted");
// this.driver.SwitchTo().ActiveElement();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.querySelector('textarea.being-eddited').innerText='Deoanca Rares'");
classroom.SendKeys("John Doe");
Console.WriteLine("Found Element");
// IJavaScriptExecutor js = new IJavaScriptExecutor();
}
catch (Exception ex)
{
IWebElement classroom = this.findElementByXPath("//*[#id='class-list-edit']");
while (!classroom.Enabled && !classroom.Displayed)
{
classroom = this.findElementByXPath("//*[#id='class-list-edit']");
}
classroom.Click();
// classroom = this.findElementByXPath("//*[#id='invited - list']");
classroom = this.findElementByClassName("being-editted");
Thread.Sleep(5000);
classroom.Click();
classroom.SendKeys("John Doe");
Console.WriteLine("Found Element");
}
}

How to get Json result in to the table using angularJs

I'm trying to retrieve whole table in mvc5 using angularJS.
Data in Json result is being displayed but not in the table as I wanted.
I'm using mvc5 and angularjs(1.x) to retrive the data from sql server
Here's the Data Access Layer code:
public List<Employee> ShowAllEmployee()
{
List<Employee> prdList = userdb.Employees.ToList();
return prdList;
}
Here's the HomeController method:
public JsonResult AllEmployee()
{
repo = new Employee_DAL.EmpRepo();
var hotList = repo.ShowAllEmployee();
List<Models.Employee> mList = new List<Models.Employee>();
foreach (var hotl in hotList)
{
Models.Employee hotLocal = new Models.Employee();
hotLocal.EmployeeId = hotl.EmployeeId;
hotLocal.FirstName = hotl.FirstName;
hotLocal.LastName = hotl.LastName;
hotLocal.Designation = hotl.Designation;
//hotLocal.Description = hotl.Description;
hotLocal.Country = hotl.Country;
hotLocal.Gender = hotl.Gender;
//hotLocal.Rating = hotl.Rating;
//hotLocal.Email = hotl.Email;
mList.Add(hotLocal);
}
return Json(mList, JsonRequestBehavior.AllowGet);
}
Here's the script ( angular) code:
var myApp = angular.module('MyModule', []);
myApp.controller('DBcontroller', function ($scope, $http) {
$http.get('/Home/AllEmployee') // added an '/' along with deleting Controller portion
.then(function (response) {
$scope.students = response.data
})
})
Here's my view(cshtml):
#{
Layout = null;
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Customs/angular.min.js"></script>
<script src="~/Customs/Scripts.js"></script>
<title>AllEmployee</title>
</head>
<body ng-app="myApp">
<div ng-controller="DBcontroller">
<table class="table-bordered">
<tr>
<th>Emp No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Designation</th>
<th>Country</th>
<th>Gender</th>
</tr>
<tr ng-repeat="e in students" #*ng-class-even="'even'" ng-class-odd="'odd'"*#>
<td>{{e.EmployeeId}}</td>
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Designation}}</td>
<td>{{e.Country}}</td>
<td>{{e.Gender}}</td>
</tr>
</table>
</div>
</body>
</html>
I expect the jsonresult to be displayed in a table. Not directly like this in the browser.Screenshot of my current output

getting data from a partial view onto main view

I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers
Tool Model
public class Tool
{
public int Id { get; set; }
public string ToolId { get; set; }
public string Adapter { get; set; }
public string Description { get; set; }
public string TNumber { get; set; }
public List<string> ComponentList { get; set; }
public List<string> AccessoryList { get; set; }
public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
public List<string> toolList = new List<string>();
}
Partial View Controller
public ActionResult PartialView()
{
Tool newTool = new Tool();
List<string> tools = new List<string>();
tools = backgroundLoad();
newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
foreach (string tool in tools)
{
newTool.ToolIdDescription = GetToolDescription(tool);
}
return View(newTool);
}
Controller to recieve Datasets
public ActionResult GetDataSet(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description =
Description.InnerText;
var Adapter =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return View(selectedTool);
}
else return View();
}
View which contains the list
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
#Html.Partial("GetDataSet", new MiniWeb.Models.Tool())
View which displays the tool information
#model MiniWeb.Models.Tool
#{
ViewBag.Title = "GetDataSet";
}
#{
ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>Tool Selection </h2>
<div class="Tool">
<span id ="id">
#Html.LabelFor(m => Model.ToolId)
#Html.TextBoxFor(modelItem => Model.ToolId)
</span>
<br/>
<span id="Description">
#Html.LabelFor(m => Model.Description)
#Html.TextBoxFor(modelItem => Model.Description)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m=> Model.Adapter)
#Html.TextBoxFor(modelItem => Model.Adapter)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m => Model.TNumber)
#Html.TextBoxFor(modelItem => Model.TNumber)
</span>
<span>
<button> Save </button>
</span>
</div>
Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.
With some more research I was able to figure out how to solve my problem. Turns out all I needed was some AJAX. I used an Ajax.Actionlink instead of an HTML action link and was able to load up my partial view in a div on the page. Here is my new view and controller. The partial view stayed the same.
View
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Ajax.ActionLink(item.Key, "_Partially", new { id = item.Key },new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "ToolInfo",
InsertionMode = InsertionMode.Replace,
})
</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
<div id="ToolInfo">
</div>
and my new controller which is returns a PartialView looks like this
Partial View Controller
public PartialViewResult _Partially(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream, Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description = Description.InnerText;
var Adapter = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return PartialView("_Partially", selectedTool);
}
return PartialView();
}
Hopefully this answer will help others like me in the future. Thanks for reading.
You're going to want to create a form on your partial view that will submit the data to the main pages controller.
You can find more information in this article.

Importing excel table to ASP.NET C# MVC

I have table in a excel sheet called ListProduct.xls. When I import the excel file I want it to print the table in success page. The index page works fine I can click on browse and lets me pick the excel file. But when I click import it gives me an error on my Product controller.
string path = Server.MapPath("~/Content/" + excelfile.FileName);
It gives me an error in this line. The error it shows is
NotSupportedException was unhandled by user code. An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code
ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using ImportExcelFileInASPNETMVC.Models;
namespace ImportExcelFileInASPNETMVC.Controllers
{
public class ProductController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelfile)
{
if (excelfile == null || excelfile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelfile.SaveAs(path);
// Read data from excel file
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<Product> listProducts = new List<Product>();
for (int row = 3; row <= range.Rows.Count; row++)
{
Product p = new Product();
p.Name = ((Excel.Range)range.Cells[row, 2]).Text;
listProducts.Add(p);
}
ViewBag.ListProducts = listProducts;
return View("Success");
}
else
{
ViewBag.Error = "File type is incorrect<br>";
return View("Index");
}
}
}
}
}
Index.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("Import", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.Raw(ViewBag.Error)
<span>Excel File </span><input type="file" name="excelfile" />
<br />
<input type="submit" value="Import" />
}
</body>
</html>
Success.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Success</title>
</head>
<body>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Name</th>
</tr>
#foreach (var p in ViewBag.ListProducts)
{
<tr>
<td>#p.Name</td>
</tr>
}
</table>
</body>
</html>
its a problem probably because of HttpPostedFileBase. Try this, post the file by keeping input[type='file'] in your #Html.BeginForm. And on server access the file using this,
var firstFile=Request.Files[0];
In addition you need to check on client as well as on server the type of file to allow (in your case it should be excel file)

Show another image onmouseover in javascript

I am having a problem with my javascript in Visual Studio. What I want to do is when i hover over the region of the country, like on this site www.pazar3.mk, a new image from that region should appear (which is transparent) with new color. I am going to post the code that I have. It doesn't return errors, but it doesn't work either. It just takes me to another .aspx site when I click on the region and it doesn't show the other image with the new color. Here's the code that I have, so please, can you tell me what I'm missing or should I change something with my code?
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 530px;
height: 380px;
z-index: 1;
left: 10px;
top: 399px;
position: absolute;
}
.auto-style2 {
width: 530px;
height: 380px;
}
</style>
<script type="text/javascript">
function newImage(arg) {
if (document.images) {
rslt = new Image();
rslt.src = arg;
return rslt;
}
}
function changeImages() {
if (document.images && (preloadFlag == true)) {
for (var i = 0; i < changeImages.arguments.length; i += 2) {
document[changeImages.arguments[i]].src = changeImages.arguments[i + 1];
}
}
}
var preloadFlag = false;
function preloadImages() {
if (document.images) {
img1 = newImage("Sliki/1.gif");
img2 = newImage("Sliki/2.gif");
img12 = newImage("Sliki/12.gif");
img23 = newImage("Sliki/23.gif");
preloadFlag = true;
}
}
</script>
</head>
<body onload="preloadImages();" >
<form id="form1" runat="server">
<div style="height: 386px; width: 906px">
<img src="Sliki/map (1).jpg" width="530" height="380" id="map"
usemap="#m_map" alt="" /><map name="m_map" id="m_map">
<area shape="poly" coords="167,335,168,321,166,318,161,313,156,308,148,308,146,304,143,302,137,301,136,293,133,283,130,277,127,273,127,270,129,266,133,261,133,253,132,248,128,242,124,240,121,240,118,243,114,248,108,254,100,258,94,261,92,261,91,268,87,274,83,279,81,281,81,286,81,291,81,295,75,298,69,304,67,308,66,316,69,318,79,319,86,319,88,321,91,324,94,326,100,325,102,322,103,317,100,315,95,314,88,312,85,308,87,303,90,300,94,297,98,294,104,293,109,293,113,295,119,303,124,311,127,318,130,327,131,335,132,338,135,336,140,332,144,331,148,331,151,333,155,336,162,336,167,335"
href="Default2.aspx" title="Resen" alt="Resen" onmouseover="changeImages('map', 'Sliki/23.gif'); return true;"
onmouseout="changeImages('map', 'Sliki/map(1).jpg'); return true;" onmousedown="changeImages('map', 'Sliki/23.gif'); return true;"
onmouseup="changeImages('map', 'Sliki/23.gif'); return true;" />
</map>
</div>
</form>

Categories