odbcconnection in ADO.NET does not contain a definition for executereader - ado.net

While creating ODBC reader in ADO.NET, as shown below:
//using bla bla bla
using System.Data.Odbc;
//some code
OdbcDataReader rdr = cmd.ExecuteReader();
//rest of the code
I get an error:
OdbcConnection does not contain a definition for 'ExecuteReader' and no extension method 'ExecuteReader' accepting a first argument of type 'OdbcConnection' could be found (are you missing a using directive or an assembly reference?
I am 100% sure I am missing no using directive nor assembly reference, I've added it myself, so why wouldn't it recognize the method?
Edit: full backend code and aspx code:
Backend C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WebApp1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cnct = new SqlConnection("Server=x.x.x.x;User ID=xx;Password=xx;Database=xxxx;"))
{
try
{
cnct.Open();
using (SqlCommand cmd = new SqlCommand("select codcli from client", cnct))
{
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string code = rdr.GetString(1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
ASPX page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApp1.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<table runat="server">
<asp:Repeater ID="repeater" runat="server">
<HeaderTemplate>
<tr class="Header">
<td>Code</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("code") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</body>
</html>
PS: I am sorry for not including the whole code from the beginning, as I am new to StackOverFlow, thank you for being patient with me

Related

Mapping some URLS with Spring Boot

Hi there im new with spring boot and mvc model im trying to create some methods to call some data to the Mongo D.B using postman im getting the data but now i want to show this data in a web page but i cant figure out how mapping works in spring boot.
I have this methods:
#Controller
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
//This method is comment because using postman get the answer in json format
// #GetMapping("/Listar")
// public List<Informacion> getAll() {
// List<Informacion> info = this.informacioRepo.findAll();
// return info;
// }
//Now this is the method that i want to work like the first one but
//instead of json answer y want to see the data in ListarInformacion page
#GetMapping("/Listar")
public String informacion(ModelMap model) {
model.addAttribute("info", informacioRepo.findAll());
return "ListarInformacion";
}
#PutMapping
public void insert(#RequestBody Informacion informacion) {
this.informacioRepo.insert(informacion);
}
}
Also i put this lines in application.properties file to set the folder where the page will be storage
spring.mvc.view.prefix=/webapp/Vistas
spring.mvc.view.suffix=.jsp
This is my ListarInformacion page
<html>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<head>
<title>Title</title>
</head>
<body>
<form:form method="GET" action="/webapp/Vistas/ListarInformacion" modelAttribute="Informacion">
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nombre</th>
<th scope="col">Identificación</th>
<th scope="col">Fecha Creación</th>
</tr>
</thead>
<c:forEach var="p" items="${info}">
<tr>
<td>${p.idInformacion}</td>
<td>${p.nombre}</td>
<td>${p.pais}</td>
<td><fmt:formatDate pattern="dd/MM/yyyy" value="${p.fechaCreacion}"/></td>
<td>
</td>
</tr>
</c:forEach>
</table>
</form:form>
</body>
</html>
this is the location of my files
can anyone tell me what am i missin because when i try to access to the url localhost:8080/Informacion/Listar the answer is a String that says /ListarInformacion ant its no redirecting me to the page that its supose to redirect
You should try to access localhost:8080/Informacion/Listar as you have already given mapping to the controller class (/Informacion)
the preferred location to put the jsp in a spring boot project is
--webapp
--WEB-INF
--jsp
--your.jsp
in your case it is
-
-webapp
--WEB-INF(Create WEB-INF directory if you don't have)
--Vistas(folder)
--jsp
--hello.jsp
And your view path in properties file will be spring.mvc.view.prefix=/WEB-INF/Vistas

ClassNotFound Exception: org.postgresql.Driver from [Module "deployment.ValidateUser.war:main" from Service Module Loader]

I am trying to connect with postgre databse with jsp program using Eclipse IDE,
I am getting this error:
"java.lang.ClassNotFoundException: org.postgresql.Driver from [Module
"deployment.ValidateUser.war:main" from Service Module Loader]".
I had put the jar files required for my project even though i am getting classnotfound exception error.
<%#page import="com.uservalidation.FarwordNames"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<%
String fname = request.getParameter("fname");
String mname = request.getParameter("mname");
String lname = request.getParameter("lname");
String dob = request.getParameter("dob");
String addr = request.getParameter("addr");
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("org.postgresql.Driver");
String conURL= "jdbc:postgresql://192.168.1.157:5432/MIPSUITE_DEV";
Connection con = DriverManager.getConnection(conURL,"mipsuitedev01","mipsuitedev01");
Statement st = con.createStatement();
//int status = st.executeUpdate("insert into users(fname,mname,lname,dob,address) values('"+fname+"',"+mname+"','"+lname+"','"+dob+"','"+addr+"')");
/* if(status>0){
out.println("Update sucessful");
}
else{
out.println("Update unsuccessful");
} */
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
It seems to be fixed the problem by removing all resteasy/jaxrs/jboss libraries from the WAR file's WEB-INF/lib/.
Put postgresql driver
jar files into WEB-INF/lib folder.
I think it's should be work for you.

Unreadable characters displaying in ASP.NET MVC

I am trying to build a store front.
StoreViewModel
public class StoreViewModel
{
public IEnumerable<GetStoreFrontItems_Result> StoreFrontItems { get; set; }
}
Index.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<StoreViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
..:: Gods Creation Taxidermy :: Store ::..
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="maintext">
<h2 class="sectionHeader2">:: Gods Creation Taxidermy : Store Items ::</h2>
<br />
At times I end up with items and mounts that the owner never came to pick up, so I put them up for sale to help generate
some revenue for Gods Creation Taxidermy.
<strong>NOTE:</strong> Now before you freak out and think I'm going to sell your mount remember the items for sale are several years old
and the owner simply didnt make the final payment or for some reason left it here.
<% Html.DataList(Model.StoreFrontItems).Columns(7).Item(item =>
{
item.Template(storeItems =>
{%>
<div style="margin-right:45px; line-height:150%;">
<span><%: Html.ActionLink(storeItems.CategoryName, "List", new { #animal = storeItems.CategoryName });%></span>
</div>
<%-- <div style="margin-right:45px; line-height:150%;">
<span><% = galleryImage.ItemName%></span>
</div>
<div style="margin-right:45px; line-height:150%;">
<span><% = galleryImage.ItemPrice%></span>
</div>--%>
<%});
}).Render(); %>
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MetaTagsContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="LeftColumnContent" runat="server">
</asp:Content>
GetStoreFrontItems_Result is generated with function import. Here is the code from Index in StoreController:
[CanonicalUrlAttribute("Store")]
[CompressionFilter(Order = 1)]
[CacheFilter(CacheDuration = 120, Order = 2)]
public virtual ActionResult Index()
{
GodsCreationTaxidermyEntities context = new GodsCreationTaxidermyEntities();
var viewModel = new StoreIndexViewModel() { StoreFrontItems = context.GetStoreFrontItems() };
return View(viewModel);
Here are some screenshots, one showing the error and the other showing what gets displayed.
As far as the error is concerned from what you have shown as code it is impossible to answer why does it happen (although the error message seems more than pretty self explanatory). As far as the garbage characters are concerned they are caused by the Compression filter you are using on your action. Here's a blog post which explains perfectly fine the reason and how to fix it.
The proposed solution is to put the following in your Global.asax to cancel the effect of ASP.NET stripping the custom compression HTTP headers that your CompressionFilter might have added in case of an exception:
protected void Application_PreSendRequestHeaders()
{
// ensure that if GZip/Deflate Encoding is applied that headers are set
// also works when error occurs if filters are still active
HttpResponse response = HttpContext.Current.Response;
if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip")
response.AppendHeader("Content-encoding", "gzip");
else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate")
response.AppendHeader("Content-encoding", "deflate");
}

Button OnClick="btnSave_Click" does not work in MVC application

I am new to MVC architecture and I am struggling to get the Button onclick. Please help me trace the issue. I have a Telerik TreeView control, which is populated. Some of the nodes have child nodes and some of them doesn't.
Please let me know what changes need to be made to fix the issue
Here I am struggling to get it working.
<%# Page Language="C#" MasterPageFile="~/Views/Shared/PostLogin.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<applications>>" %>
<%# Import Namespace="ApplicationGrps" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<script runat="server" type="text/javascript">
protected void Page_Load()
{
ApplicationGrps.Visible = true;
ApplicationGrps.DataSource = ODS1;
ApplicationGrps.DataFieldID = "ApplicationName";
ApplicationGrps.DataFieldParentID = "ParentID";
ApplicationGrps.DataBind();
BindCheckedTags(ApplicationGrps);
}
protected void BindCheckedTags(RadTreeView treeView)
{
// Displays the checked nodes
}
protected void ODS2_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["ClientID"] = ViewData["ClientID"];
}
protected void btnSave_Click(object sender, EventArgs e)
{
//Iterate through the tree and get all the nodes that are checked and submit it.
}
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="HeadContent" runat="server">
<link href="<%: Url.Content("~/Content/script-libraries/jquery-ui-1.7.2.custom/css/smoothness/jquery-ui-1.7.2.custom.css") %>"
rel="stylesheet" type="text/css" />
<script src="<%: Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<telerik:RadTreeView id="AppModulesTreeView" runat="server" CheckBoxes="True" Visible="true" >
</telerik:RadTreeView>
<asp:ObjectDataSource ID="ODS1" runat="server"
SelectMethod="GetAllApplicationModules"
TypeName="ELS.BOS.Services.EntitlementProxy.EntitlementServiceClient">
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="ODS2" runat="server"
SelectMethod="GetApplicationModMappedByClientID"
TypeName="ELS.BOS.Services.EntitlementProxy.EntitlementServiceClient"
onselecting="ODS2_Selecting">
<SelectParameters>
<asp:Parameter Name="ClientID" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<%-- <telerik:RadButton runat="server" onclick="btnSave_Click"
Text="Save">
</telerik:RadButton>
<telerik:RadButton ID="btnCancel" runat="server" Text="Cancel"
>
</telerik:RadButton>--%>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnSave_Click" />
</div>
</form>
</asp:Content>
Please let me know if I need to use javascript or jquery to get this working. Please show me some samples on how to fire btnSave_click on button control click.
Thanks!
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnSave_Click" />, asp:ObjectDataSource, ScriptManager, ... in an ASP.NET MVC application?
No.
In an ASP.NET MVC applications you don't use server side controls (no runat="server"). You don't PostBack. There is no ViewState. There is no code behind. There are no events. There are no script managers. There are no object data sources. All this is specific to WebForms and is no longer used in MVC.
In an ASP.NET MVC application you have a Controller, a Model and a View. The view contains standard HTML markup which could be generated with the aid of HTML helpers. To call the controller you could use a normal link:
<%= Html.ActionLink("link text", "actionName", "controllerName") %>
The controller contains actions which manipulate the model and choose the view to be rendered by passing it all the information it needs to show.
I would strongly recommend you start reading the tutorials here: http://asp.net/mvc about how MVC works and familiarize yourself with the very basics of this framework.

Problem with Image uploading to SQL

I have problem with uploading image to SQL database.
i have Methods Upload in controller Upload
dbData userDb = new dbData();
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileWrapper file)
{
if (file.ContentLength > 0)
{
Stream fileStream = file.InputStream;
string fileName = Path.GetFileName(file.FileName);
int fileLength = file.ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
var image = new ImageTable();
image.Image = fileData;
image.Description = "Default profile picture";
try
{
userDb.ImageTables.InsertOnSubmit(image);
userDb.SubmitChanges();
return RedirectToAction("Success");
}
catch (Exception ex)
{
throw;
}
}
return View();
}
If i use this view page
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Upload</title>
</head>
<body>
<div>
<% using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input name="file" type="file" runat="server" id="file"/><br />
<input type="submit" value="Upload File" />
<%} %>
</div>
</body>
</html>
everithing works great but if i want to use view runned on masterpage i wil get this error after i click upload submit button:
No parameterless constructor defined for this object.
Know someone where is problem and how can i fix it ?
Thanks
This error occurs because default model binder can't create instances of classes that don't contain parameterless constructor (such as HttpPostedFileWrapper).
Simplest way around this is to just pull files from Request.Files (e.g. Request.Files["file"]).
Alternatively, you could create custom model binder for that.
UPDATE:
This is action method I used:
[HttpPost]
public ActionResult Index(FormCollection form)
{
var file = Request.Files["file"];
if(file != null && file.ContentLength > 0)
{
// ...
}
return View();
}