The name does not exist in the current context - oracle

I'm trying to upload files to Oracle database Using C# vs2012. Its my first time I do so especially with Oracle. I just followed an example I found online but I got some errors before I even run the codes showing me that some of the type or name spaces don't exist.
The example I followed : Blob Example
Here are the codes that are underlined red in my Resources_to_upload.aspx.cs
objCmd
objConn
My 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.OracleClient;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
public partial class Resources_to_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
try
{
if (fileUploadDocument.PostedFile.ContentLength > 0)
{
// Get the File name and Extension
string FileName = Path.GetFileName(fileUploadDocument.PostedFile.FileName);
string FileExtension = Path.GetExtension(fileUploadDocument.PostedFile.FileName);
//
// Extract the content of the Document into a Byte array
int intlength = fileUploadDocument.PostedFile.ContentLength;
Byte[] byteData = new Byte[intlength];
fileUploadDocument.PostedFile.InputStream.Read(byteData, 0, intlength);
//
// Save the file to the DB
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
object Conn = new OracleConnection(strConn);
//
StringBuilder strQueryBuilder = new StringBuilder("INSERT INTO RESOURCES(RESOURCES_ID, FILE_NAME, TYPE, RESOURCE_FILE) VALUES (");
strQueryBuilder.Append("'1', ");
strQueryBuilder.Append("'" + FileName + "', ");
strQueryBuilder.Append("'" + FileExtension + "', ");
strQueryBuilder.Append(" :RESOURCE_FILE)");
String strQuery = strQueryBuilder.ToString();
//
OracleParameter blobParameter = new OracleParameter();
blobParameter.ParameterName = "Resources_FILE";
blobParameter.OracleType = OracleType.Blob;
blobParameter.Direction = ParameterDirection.Input;
blobParameter.Value = byteData;
objCmd = new OracleCommand(strQuery, objConn);
objCmd.Parameters.Add(blobParameter);
//
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
//
lblMsg.Text = "Document Uploaded Succesfully";
}
}
catch (Exception ex)
{
lblMsg.Text = " Error uploading Document: " + ex.Message.ToString();
}
}
}
Please help solve this issue. Thank you

StringBuilder is in the System.Text namespace. So you can either reference it explicitly:
System.Text.StringBuilder strQueryBuilder ...
Or add a using directive to the file:
using System.Text
...
StringBuilder strQueryBuilder ...
As for objCmd and objConn, where do you define those? They're not created in the code you posted. You do create a connection object here:
object Conn = new OracleConnection(strConn);
Maybe you mean to use Conn instead of objConn? But you don't create a command object anywhere. You need to declare and instantiate variables before you can use them.

Related

Call is not passing from controller to model in web api

I am totally new in web api. I have created web api simply to retrive data from oracle DB with the help of few articles which i found on internet. I am trying to find out error since morning but no success till now. When i try to run the code, it dont give any error or anything. Debugger passed to my DB class and stops. Below is my controller code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
namespace iLearnWebApi.Controllers
{
public class ValuesController : ApiController
{
DAL.DBAccess dblayer = new DAL.DBAccess();
public DataSet Getrecord(int programid)
{
DataSet ds = dblayer.GetRecordbyid(programid);
return ds;
}
} }
And below is my DBClass code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Configuration;
using System.Data.Odbc;
using Oracle.ManagedDataAccess.Client;
namespace iLearnWebApi.DAL
{
public class DBAccess
{
OracleParameter[] _objOraParam;
OracleConnection con = new OracleConnection();
//--- Get Records By Program ID
public DataSet GetRecordbyid(int progid)
{
DataSet ds = new DataSet();
try
{
_objOraParam = new OracleParameter[2];
_objOraParam[0] = new OracleParameter("p_Program_ID", OracleDbType.Int32);
_objOraParam[0].Direction = ParameterDirection.Input;
_objOraParam[0].Value = progid;
_objOraParam[1] = new OracleParameter("RCT_OUT", OracleDbType.RefCursor);
_objOraParam[1].Direction = ParameterDirection.Output;
ds = ExecuteDataset(con, CommandType.StoredProcedure, "ILS_USP_PROGRAM_DATA", _objOraParam);
}
catch (Exception ex)
{
LogError("GetRecordbyid", ex.Message.ToString());
throw ex;
}
finally
{
con.Close();
}
return ds;
}
// Execute Data
private DataSet ExecuteDataset(OracleConnection con, CommandType procname, string commandText, params OracleParameter[] objOraParam)
{
//create a command and prepare it for execution
OracleCommand cmd = new OracleCommand();
PrepareCommand(cmd, con, (OracleTransaction)null, procname, commandText, objOraParam);
//create the DataAdapter & DataSet
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
cmd.Dispose();
//return the dataset
return ds;
}
//---- Used To Prepare Oracle command
private void PrepareCommand(OracleCommand command, OracleConnection connection, OracleTransaction transaction, CommandType commandType, string commandText, OracleParameter[] commandParameters)
{
//if the provided connection is not open, we will open it
string con_string = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = DecryptString(con_string, "CFSENC");
connection.Open();
}
//associate the connection with the command
command.Connection = connection;
//set the command text (stored procedure name or Oracle statement)
command.CommandText = commandText;
//if we were provided a transaction, assign it.
if (transaction != null)
{
command.Transaction = transaction;
}
//set the command type
command.CommandType = commandType;
//attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
}
// Used For Attaching Parameter To Command
private void AttachParameters(OracleCommand command, OracleParameter[] commandParameters)
{
foreach (OracleParameter p in commandParameters)
{
//check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
// Used For Decryption Of Encrypted String
private string DecryptString(string con_string, string key)
{
byte[] plainBytes = null;
try
{
string passWord = key;
string strInput = con_string;
byte[] encryptBytes = Convert.FromBase64String(strInput);
MemoryStream ms = new MemoryStream(strInput.Length);
//Using triple des for decryption
TripleDESCryptoServiceProvider tDesCsp = new TripleDESCryptoServiceProvider();
// Creating decryption IV and Key using the key supplied by the user
tDesCsp.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(passWord, new byte[0]);
tDesCsp.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
CryptoStream deEnStream = new CryptoStream(ms, tDesCsp.CreateDecryptor(), CryptoStreamMode.Write);
//write the decrypted data to the stream
deEnStream.Write(encryptBytes, 0, encryptBytes.Length);
deEnStream.FlushFinalBlock();
plainBytes = new byte[ms.Length];
ms.Position = 0;
//reading the decrypted stream and write it into the byte array
ms.Read(plainBytes, 0, (int)ms.Length);
deEnStream.Close();
}
catch (Exception err)
{
string sErr = err.ToString();
throw new Exception("Error decrypting string.");
}
return Encoding.UTF8.GetString(plainBytes);
}
// For Writing Log Files
private void LogError(string header, string error)
{
string strPath;
string strActualError;
StreamWriter objErrWriter;
DateTime objDt = DateTime.Now;
string strDate;
strDate = objDt.ToString("ddMMyyyy");
try
{
// Get Actual Path of "Error" stored in Web.config
strPath = ConfigurationManager.AppSettings["sPathErrorLog"];
//Generates Path & LogFile Name of ErrorLog
strPath = strPath + strDate + ".log";
// Generates Error Message
strActualError = DateTime.Now + " : " + header + " : " + error;
// Creation of File.
objErrWriter = new StreamWriter(strPath, true, System.Text.Encoding.ASCII);
objErrWriter.WriteLine("");
objErrWriter.WriteLine(strActualError);
objErrWriter.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}}
Can anyone please tell me what mistake i have done in above code.
This sounds like a routing issue (without seeing your route config).
Try changing: public DataSet Getrecord(int programid)
To: public DataSet Get(int id)
And call: localhost:60908/api/Values/1

Searching VARCHAR2 in oracle 11g DB

I am seraching varchar2 column "DF_FORM_COMP_VALUE" that includes ID Number with address to retrieve data by searching according to the ID Number only in oracle 11g DB. I built the following code to retrieve the data
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.OracleClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String mycon = "DATA SOURCE=mydatasource/example;USER
ID=user;Password=mypassword;Unicode=True";
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR =" +
TextBox1.Text;
OracleConnection con = new OracleConnection(mycon);
OracleCommand cmd = new OracleCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Label1.Text = "Particular ID found successfully";
Label2.Text = ds.Tables[0].Rows[0]["ID_TRANSACTION"].ToString();
Label3.Text = ds.Tables[0].Rows[0]["ID_FORM_COMPONENT"].ToString();
Label4.Text = ds.Tables[0].Rows[0]["ID"].ToString();
}
else
{
Label1.Text = "ID Not Found - Please Serach Again";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
}
con.Close();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
it keeps throwing Error ORA-01722: invalid number! Can someone help please
I'm assuming TextBox1.Text is some sort of input from the user on a web page somewhere? If the contents of that variable are "x", you're going to wind up with this query:
Select * From DF_FORM_COMP_VALUE Where VALUE_STR = x
That's not going to work because you need the string "x", but here it looks like a variable.
You probably want this line to look like:
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR = '" +
TextBox1.Text + "'";
THIS IS A VERY BAD IDEA. DO NOT DO THIS.
You need to read up on SQL Injection. Never put unsafe, user-specified text directly into a SQL query. Doing so will make your application trivially hackable.
I'm not sure what you're using to connect to Oracle, but you want to create a parameterized query and put the user input as a bind variable. One example on doing that is here. So you really want your query to look like this:
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR = :myinput"
Then you bind TextBox1.Text to :myinput, depending on what you're using to access Oracle. This is also more efficient if you run the query multiple times, because your query will not need to be hard parsed each time it is executed.

Show image from SQL Server 2008 in datagridview C#

I'm tired of searching for a solution. please help me.
I have a table with columns
p_id (int)
p_name (varchar50)
category (int)
price (money)
picture (Image)
Insertion process works perfectly, it is also showing me my database records.. but it sow me my filepath in gridview rather than show image...
Please help me... it is part of my project... and I don't know how to show retrieve image from database in Datagridview
I have done all my SQL connection work in Dall Class
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Image_task
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void insert_btn_Click(object sender, EventArgs e)
{
try
{
int count;
dall insert = new dall();
int id = Convert.ToInt32(id_txt.Text);
string name = name_txt.Text;
int cat = Convert.ToInt32(cat_txt.Text);
decimal price = Convert.ToDecimal(price_txt.Text);
string image=pic_txt.Text;
count = insert.insrt_up_del("insert into product values('" + id + "','" + name + "','" + cat + "','" + price + "','" + image + "')");
MessageBox.Show("Insert Successfully", "Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
insert_btn.Enabled=false;
}
private void browse_txt_Click(object sender, EventArgs e)
{
insert_btn.Enabled = true;
openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" + "All files (*.*)|*.*";
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
pic_txt.Text = openFileDialog1.FileName;
}
}
private void search_btn_Click(object sender, EventArgs e)
{
dall select = new dall();
DataTable dt = new DataTable();
dt = select.select("Select * from product");
dataGridView1.DataSource = dt;
//DataGridViewImageColumn img = new DataGridViewImageColumn();
//img.DataPropertyName = "Picture";
//img.Width = 200;
//img.HeaderText = "Picture Column";
//img.ReadOnly = true;
//img.ImageLayout = DataGridViewImageCellLayout.Normal;
//dataGridView1.Columns.Add(img);
//dataGridView1.DataSource = new BindingSource(dt,null);
}
}
}
use data adapter
DataAdapter da = new DataAdapter("Select * from product",youconnection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile'

I am following http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files. Using VS2010, ASP.NET 4.0, MVC3 in C# with ADO.NET in SQL Server 2008R2. I am getting the following error message...
'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile' accepting a first argument of type 'System.Web.HttpPostedFileBase' could be found (are you missing a using directive or an assembly reference?)
I searched through Stackflow, there was something about including System.Web.Abstractions. I included this and I still getting the error.
Thanks in advance if anyone can tell me the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.SqlClient;
using System.Web.Helpers;
namespace MvcApplication1.Controllers
{
public class MyController : Controller
{
//
// GET: /My/
public ActionResult Index()
{
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string mimeType = Request.Files[upload].ContentType;
Stream fileStream = Request.Files[upload].InputStream;
string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (#FileContent, #MimeType, #FileName)";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#FileContent", fileData);
cmd.Parameters.AddWithValue("#MimeType", mimeType);
cmd.Parameters.AddWithValue("#FileName", fileName);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return View();
}
public FileContentResult GetFile(int id)
{
SqlDataReader rdr; byte[] fileContent = null;
string mimeType = ""; string fileName = "";
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = #ID";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#ID", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
fileContent = (byte[])rdr["FileContent"];
mimeType = rdr["MimeType"].ToString();
fileName = rdr["FileName"].ToString();
}
}
return File(fileContent, mimeType, fileName);
}
}
}
in the Helpers folder I have the Helper class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public static class Helper
{
public static bool HasFile(this HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0) ? true : false;
}
}
You need to add a using statement to your MyController code file, as that is what is required when you want to use an extension method (it needs to be in scope):
using MvcApplication1.Models;

how can i auto genrete a number in vb.net?

i want to genrete a auto number in my project....
i used vb .net 2008 and SQl server 2005 as backend ??
i want to create a serial no that is like abc/2010/01..In this..
the abc is same in all the serial no.
the 2010 is used from the running Year.(using date for year)
the 01 is a actual serial no that can be auto genrete...
But how can i do this ....??
and How can i find max number from my serial no.....???
how can i maintain it if i delete it then all after delete serial no will place it's place..(there is no break in serial no on delete)
??????
Please help me.....
here is the code snippet for generate newid
i have taken a simple label and textbox
label will auto generate newid and textbox will insert a new record in database
take a label and textbox in your design page
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.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
public static int temp;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
newcode();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=practice;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("Insert into frmlogin(id,username) values ("+ temp+",'"+TextBox1.Text+"')", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("username", TextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
Label1.Text = "";
newcode();
}
public void newcode()
{
SqlConnection con1 = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=practice;Integrated Security=True;");
con1.Open();
SqlCommand cmd2 = new SqlCommand("Select Max(id) as empid from frmlogin", con1);
cmd2.CommandType = CommandType.Text;
SqlDataReader r = cmd2.ExecuteReader();
r.Read();
if (r["empid"].ToString() != "")
{
temp = int.Parse(r["empid"].ToString()) + 1;
}
else
{
temp = 1;
}
Label1.Text= temp.ToString();
r.Close();
con1.Close();
}
}
The main thing is that you should maintain your incremented number somewhere, In my case i have used textbox and label.
But I did rather recommend you to go for GUID or Random Number.
for GUID :
System.Guid.NewGuid().ToString();
Have Look here as well
for Random Number Generation
::: Program that uses Random type [C#] :::
using System;
class Program
{
static void Main()
{
Random random = new Random();
Console.WriteLine(random.Next());
Console.WriteLine(random.Next());
}
}
::: Output of the program :::
1592498984
1526415661
Try this
You could store the serial numbers in a database table where the third component of the number is the primary key of the table as an identity field. Any time you create a new serial number, you'd insert the current year and the static text into the table. An easy way to do this would be to wrap that logic in a stored procedure which takes no arguments, internally inserts the current year and the text, and returns the entire serial number as a single scalar value.
Something like:
INSERT INTO SerialNumbers (Year, Name) VALUES (year(getdate()), 'abc')
and:
SELECT Name + '/' + CAST(Year AS nvarchar) + '/' + CAST(ID AS nvarchar) FROM SerialNumbers WHERE ID = SCOPE_IDENTITY()

Resources