Oracle database over ODBC converts non-english characters to question marks - oracle

I am working on retrieving data from an Oracle data source, however I am having issues with non-english characters being replaced with question marks. Some background:
I am pulling data from an Oracle view whose columns are defined as VARCHAR2
When accessing said view through Oracle SQL Developer, the results display properly
I have attempted to update my System.Web.Odbc to the latest version to no avail
I am aware that the console does not properly display certain Unicode characters, but even viewing the raw data using breakpoints shows said characters replaced with '?'
Here is a runnable example with some specific implementation details removed:
using System;
using System.Data;
using System.Data.Odbc;
namespace OdbcTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Trying ODBC Connection");
DataTable odbcData = GetData("SELECT NAME as name FROM SYSADM.[ViewName] WHERE TRUNC(sysdate) - to_date(HIRE_DT) BETWEEN 0 AND 20");
Console.WriteLine(odbcData.Rows.Count.ToString() + "rows extracted.");
foreach (DataRow dataRow in odbcData.Rows)
{
foreach (var item in dataRow.ItemArray)
{
Console.WriteLine(item);
}
}
Console.ReadKey();
}
public static DataTable GetData(string SQLStatement)
{
try
{
using (System.Data.Odbc.OdbcConnection connection = new OdbcConnection([DSN Details]))
{
DataSet ds = new DataSet();
OdbcCommand command = new OdbcCommand(SQLStatement, connection);
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
command.CommandTimeout = 600;
connection.Open();
adapter.Fill(ds);
connection.Close();
return ds.Tables[0];
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Related

Spring jdbc 'select for update'

I have the following method that I use with Spring JDBC
public String getState() {
String stateLink = template.queryForObject(
"select state_url from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1",
(result, rowNum) -> {
return result.getString("state_url");
});
return stateLink;
}
I can't find an example of how to do a for update with Spring JDBC. I want in_use to be set to true using for update.
I need to use select for update since this application will be used in a multi-threaded fashion. I don't want more than one thread to get the same row and the way to prevent that is by using select for update
I was able to do this with plain JDBC, here is the question I asked how to do it with plain JDBC
select "for update" with JDBC?
Anyone know how this would be done?
This is what I came up with, feel free to recommend improvements
public String getState() throws SQLException {
String state = null;
Connection conn = DataSourceUtils.getConnection(template.getDataSource());
try {
conn.setAutoCommit(false);
String[] colNames = { "id", "state_url", "in_use" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1 FOR UPDATE";
System.out.println(query);
try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
// Get the current values, if you need them.
state = rs.getString(colNames[1]);
rs.updateBoolean(colNames[2], true);
rs.updateRow();
conn.commit();
}
}
} catch (SQLException e) {
conn.setAutoCommit(true);
e.printStackTrace();
} finally {
conn.setAutoCommit(true);
}
return state;
}

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

How do I combine Domino view data and JDBC query in a repeat control

Currently, I have a repeat control with computed fields that display column values from a Domino view. In each row in the repeat control I have another computed field that executes a SQL query that returns a value from a SQL table. The SQL query has a parameter that uses one of the column values from the Domino view.
For the SQL computed field I wrote a function that instantiates a JDBC connection and then executes a SQL query for each row in the repeat control. The function looks like this (the pTextNo argument comes from one of the column values in the Domino view):
function getFormulaTextDetailRows(pTextNo){
if(pTextNo == null){return ""};
var con:java.sql.Connection;
try {
con = #JdbcGetConnection("as400");
vStatement = "SELECT TXSQN, TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? ORDER BY TXSQN";
var vParam = [pTextNo];
var resultset:java.sql.ResultSet = #JdbcExecuteQuery(con, vStatement, vParam);
var returnList = "<ul>";
//format the results
while(resultset.next()){
returnList += ("<li>" + resultset.getString("TXDTA").trim() + "</li>");
}
returnList += "</ul>";
}catch(e){
returnList = e.toString()
}finally{
con.close();
}
return returnList;
}
This works fine but I'm sure this isn't the most efficient way of utilising the JDBC connection. Opening and closing a JDBC connection on each row in the repeat control isn't right and I'm concerned that when more than one person opens the XPage the server will run into difficulties with the number of open connections.
After doing some research on the internet it seems I should be using a jdbcConnectionManager on the page.
I added a jdbcConnectionManager to my custom control and also added a jdbcQuery data source to the panel that holds the repeat control. The jdbcConnectionManager looks like this:
<xe:jdbcConnectionManager
id="jdbcConnectionManager1"
connectionName="as400">
</xe:jdbcConnectionManager>
And the jdbcQuery data source looks like this:
<xe:jdbcQuery
var="jdbcProcessText"
scope="request"
calculateCount="true"
sqlQuery="SELECT TXSQN,TXDTA FROM DOMINO.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN"
connectionManager="jdbcConnectionManager1">
<xe:this.sqlParameters>
<xe:sqlParameter value="#{javascript:requestScope.processTextNo}">
</xe:sqlParameter>
</xe:this.sqlParameters>
</xe:jdbcQuery>
My computed field's value property in the repeat control looks like this:
requestScope.processTextNo = textrow.getDocument().getItemValueString('ProcessTextNo');
var vCount = jdbcProcessText.getCount();
var returnList = "<ul>";
for(i=0; i<vCount; i++){
returnList += ("<li>" + jdbcProcessText.get(i).getColumnValue("TXDTA") + "</li>");
}
returnList += "</ul>";
return returnList;
The problem I've run into is that I don't get any data from the JDBC query at all. Even if I hard code a value I know exists in the SQL table in the sqlParameter property of the jdbcQuery object I still get no results. I suspect I'm not calling the jdbcQuery object correctly but I can't figure out how to do so. Any help will be greatly appreciated.
You may want to reconsider your approach. I would suggest creating a Java bean to get the Domino view data, loop through that and call out to your query for each row in the view. Build up a List (Java List) of a Row class that has all the data you want to show. Then in the repeat call to your Java bean to a method that returns the List of Row classes. In each control in the repeat you would call to the getXXX method in your Row class. This way you can quickly build the List the repeat works on. Doing it your way in the control in the repeat will be very slow.
Howard
Here's the bean I wrote to do the job. At the start it opens a connection to the SQL data source, grabs a viewEntryCollection using a document UNID as a key, and then puts the column values into a HashMap for each row in the viewEntryCollection. One of the values in the HashMap is pulled from a SQL query. My repeat control iterates over the List returned by the bean. In other words the bean returns a List of HashMaps where most of the values in each HashMap comes from Domino view entry data and one value comes from SQL (not sure if that's the correct way of saying it, but it makes sense to me!).
Here's my code:
package com.foo;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewEntry;
import lotus.domino.ViewEntryCollection;
import com.ibm.xsp.extlib.relational.util.JdbcUtil;
import com.ibm.xsp.extlib.util.ExtLibUtil;
public class ProcessTextLines implements Serializable {
private static final long serialVersionUID = 1L;
private Connection conn = null;
public int rowCount = 0;
public int getRowCount() {
return rowCount;
}
// public void setRowCount(int rowCount) {
// this.rowCount = rowCount;
// }
public ProcessTextLines() {
/*
* argumentless constructor
*/
try {
// System.out.println("ProcessTextLines.java - initialising connection to as400");
this.conn = this.initialiseConnection();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (this.conn != null) {
// System.out.println("ProcessTextLines.java - closing connection to as400");
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public List<HashMap<String, String>> getRows(final String unid)
throws NotesException {
List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("luProductMasterFormula");
view.setAutoUpdate(false);
ViewEntryCollection vec = view.getAllEntriesByKey(unid, true);
ViewEntry ve = vec.getFirstEntry();
while (ve != null) {
result.add(processRowVals(ve));
rowCount++;
ViewEntry tmp = vec.getNextEntry(ve);
ve.recycle();
ve = tmp;
}
view.recycle();
db.recycle();
vec.recycle();
} catch (NotesException e) {
e.printStackTrace();
}
return result;
}
/*
* Create a HashMap of names + column values from a ViewEntry
*/
#SuppressWarnings("unchecked")
private HashMap<String, String> processRowVals(ViewEntry ve) {
HashMap<String, String> processRow = new HashMap<String, String>();
try {
Vector cols = ve.getColumnValues();
processRow.put("sequenceNo", cols.get(1).toString());
processRow.put("textNo", cols.get(3).toString());
processRow.put("status", cols.get(6).toString());
processRow.put("textLines", getProcessTextLines(cols.get(3).toString()));
// unid of the entry's doc
processRow.put("unid", ve.getUniversalID());
} catch (NotesException e) {
e.printStackTrace();
}
return processRow;
}
private Connection initialiseConnection() throws SQLException {
Connection connection = null;
try {
connection = JdbcUtil.createNamedConnection(FacesContext
.getCurrentInstance(), "as400");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
private String getProcessTextLines(String textNo) {
String resultHTML = "<ul class=\"processTextList\">";
try {
// System.out.println("ProcessTextLines.java - setting SQL parameter: " + textNo);
PreparedStatement prep = conn
.prepareStatement("SELECT TXSQN,TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN");
// supply a value to the PreparedStatement's parameter (the first
// argument is 1 because it is the first parameter)
prep.setString(1, textNo);
ResultSet resultSet = prep.executeQuery();
while (resultSet.next()) {
resultHTML += ("<li>" + resultSet.getString("TXDTA").trim() + "</li>");
}
} catch (SQLException e) {
// e.printStackTrace();
}
resultHTML += "</ul>";
return resultHTML;
}
}
It took me a while because of my lack of Java knowledge but with the pointers #Howard gave plus the few bits and pieces I found on the web I was able to cobble this together.
Opening and closing the SQL connection in the constructor feels counter intuitive to me, but it seems to work.

install nopcommerce with oracle

hello I downloaded the solution nopCommerce an e-commerce open source which achievement operate and install without problems with MSSQLSERVER database however I would like to implement with ORACLEdatabase
Official Site http://www.nopcommerce.com/
I have been guiding me this post
http://www.nopcommerce.com/boards/t/17712/mysql-support.aspx
I have tried to follow the steps indicated for mysql and adapt to oracle yet one of the first things that tells me is the creation of two classes
OracleConnectionFactory:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Data.Common;
using Oracle.DataAccess.Client;
namespace Nop.Data
{
public class OracleConnectionFactory : IDbConnectionFactory
{
private readonly string _baseConnectionString;
private Func<string, DbProviderFactory> _providerFactoryCreator;
public OracleConnectionFactory()
{
}
public OracleConnectionFactory(string baseConnectionString)
{
this._baseConnectionString = baseConnectionString;
}
public DbConnection CreateConnection(string nameOrConnectionString)
{
string connectionString = nameOrConnectionString;
bool treatAsConnectionString = nameOrConnectionString.IndexOf('=') >= 0;
if (!treatAsConnectionString)
{
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder(this.BaseConnectionString);
//MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(this.BaseConnectionString);
//builder.Server = nameOrConnectionString;
connectionString = builder.ConnectionString;
}
DbConnection connection = null;
try
{
connection = this.ProviderFactory("Oracle.DataAccess.Client").CreateConnection();
connection.ConnectionString = connectionString;
}
catch
{
//connection = new MySqlConnection(connectionString);
connection = new OracleConnection(connectionString);
}
return connection;
}
public string BaseConnectionString
{
get
{
return this._baseConnectionString;
}
}
internal Func<string, DbProviderFactory> ProviderFactory
{
get
{
Func<string, DbProviderFactory> func1 = this._providerFactoryCreator;
return delegate(string name)
{
return DbProviderFactories.GetFactory(name);
};
}
set
{
this._providerFactoryCreator = value;
}
}
}
}
OracleProvider :
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web.Hosting;
using Nop.Data.Initializers;
using Oracle.DataAccess.Client;
using Nop.Core.Data;
namespace Nop.Data
{
public class OracleDataProvider : IDataProvider
{
#region Utilities
protected virtual string[] ParseCommands(string filePath, bool throwExceptionIfNonExists)
{
if (!File.Exists(filePath))
{
if (throwExceptionIfNonExists)
throw new ArgumentException(string.Format("Specified file doesn't exist - {0}", filePath));
else
return new string[0];
}
var statements = new List<string>();
using (var stream = File.OpenRead(filePath))
using (var reader = new StreamReader(stream))
{
var statement = "";
while ((statement = readNextStatementFromStream(reader)) != null)
{
statements.Add(statement);
}
}
return statements.ToArray();
}
protected virtual string readNextStatementFromStream(StreamReader reader)
{
var sb = new StringBuilder();
string lineOfText;
while (true)
{
lineOfText = reader.ReadLine();
if (lineOfText == null)
{
if (sb.Length > 0)
return sb.ToString();
else
return null;
}
//MySql doesn't support GO, so just use a commented out GO as the separator
if (lineOfText.TrimEnd().ToUpper() == "-- GO")
break;
sb.Append(lineOfText + Environment.NewLine);
}
return sb.ToString();
}
#endregion
#region Methods
public virtual void InitConnectionFactory()
{
//var connectionFactory = new SqlConnectionFactory();
var connectionFactory = new OracleConnectionFactory();
//TODO fix compilation warning (below)
#pragma warning disable 0618
Database.DefaultConnectionFactory = connectionFactory;
}
/// <summary>
/// Initialize database
/// </summary>
public virtual void InitDatabase()
{
InitConnectionFactory();
SetDatabaseInitializer();
}
/// <summary>
/// Set database initializer
/// </summary>
public virtual void SetDatabaseInitializer()
{
//pass some table names to ensure that we have nopCommerce 2.X installed
var tablesToValidate = new[] { "Customer", "Discount", "Order", "Product", "ShoppingCartItem" };
//custom commands (stored proedures, indexes)
var customCommands = new List<string>();
//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests
customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/Install/SqlServer.Indexes.sql"), false));
//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests
customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/Install/SqlServer.StoredProcedures.sql"), false));
var initializer = new CreateTablesIfNotExist<NopObjectContext>(tablesToValidate, customCommands.ToArray());
Database.SetInitializer(initializer);
}
/// <summary>
/// A value indicating whether this data provider supports stored procedures
/// </summary>
public virtual bool StoredProceduredSupported
{
get { return true; }
}
/// <summary>
/// Gets a support database parameter object (used by stored procedures)
/// </summary>
/// <returns>Parameter</returns>
public virtual DbParameter GetParameter()
{
//return new SqlParameter();
return new OracleParameter();
}
#endregion
}
}
also i installed the managed nuget package like this link said
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/CodeFirst/index.html
oracle odp.net managed driver
in nop.data and nop.web
I appreciate any help freshened up the steps I need to do or that I may be going
one of the first thing i trying is the Oracle provider recognize and achieve connect to my database
It was an interesting question. Using nop commerce with Oracle is technically possible, but it would be a very wild ride for you.
Good news first. Nop Commerce is architectured based on repository pattern. Basically Nop.Data abstracts all the SQL Server related data access. You would need to re-write this almost entirely.
Not so good news next. Search, Paging, Catalog listing uses a stored procedure in SQL Server. You may need to re-write it completely. And most of the time, you are on your own. Unless if you are confident with Oracle and .Net EF, it would be a really wild ride.
I would say, its less problem if you want to stick with SQL Server. I understand sometime you may not make technical decision. So you can explain clearly about complexity and effort needed to migrate to the person makes that decision.
Source: NopCommerce developer for last 2.5years.

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