Search Results

Search found 191 results on 8 pages for 'storedprocedure'.

Page 8/8 | < Previous Page | 4 5 6 7 8 

  • Input string was not in a correct format.

    - by Jon
    I have this error which doesn't happen on my local machine but it does when the code is built by our build sever and deployed to the target server. I can't work out what the problem is, after having spent many hours on this issue. Here is an error trace: [FormatException: Input string was not in a correct format.] System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +7469351 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119 System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info) +35 System.String.System.IConvertible.ToByte(IFormatProvider provider) +46 System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) +199 System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges) +127 System.Web.UI.WebControls.Parameter.GetValue(Object value, Boolean ignoreNullableTypeChanges) +66 System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control) +285 System.Web.UI.WebControls.SqlDataSourceView.InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) +251 System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +476 System.Web.UI.WebControls.SqlDataSource.Select(DataSourceSelectArguments arguments) +19 Customer_NewTenancyList.BindReport(GridSortEventArgs e) +442 Customer_NewTenancyList.Page_Load(Object sender, EventArgs e) +345 System.Web.UI.Control.OnLoad(EventArgs e) +73 baseRslpage.OnLoad(EventArgs e) +16 System.Web.UI.Control.LoadRecursive() +52 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2170 Here is my own trace: Begin PreInit aspx.page End PreInit 3.12888928620816E-05 0.000031 aspx.page Begin Init 7.43111205474439E-05 0.000043 aspx.page End Init 0.00122138428208054 0.001147 aspx.page Begin InitComplete 0.00125379063540199 0.000032 aspx.page End InitComplete 0.00127781603527823 0.000024 aspx.page Begin PreLoad 0.00131022238859967 0.000032 aspx.page End PreLoad 0.00133424778847591 0.000024 aspx.page Begin Load 0.00135575890231859 0.000022 Page_Load 0.00145996209015392 0.000104 BindReport 0.0014856636807192 0.000026 Parameters add start: 30/03/2010 30/04/2010 0.0015569017850034 0.000071 Parameters add ended 0.00160048274291844 0.000044 Trace 1 0.00162450814279468 0.000024 Unhandled Execution Error Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info) at System.String.System.IConvertible.ToByte(IFormatProvider provider) at System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) at System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges) at System.Web.UI.WebControls.Parameter.GetValue(Object value, Boolean ignoreNullableTypeChanges) at System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control) at System.Web.UI.WebControls.SqlDataSourceView.InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) at System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) at System.Web.UI.WebControls.SqlDataSource.Select(DataSourceSelectArguments arguments) at Customer_NewTenancyList.BindReport(GridSortEventArgs e) at Customer_NewTenancyList.Page_Load(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at baseRslpage.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) And here is my code: Trace.Warn("BindReport") Dim sds As New SqlDataSource sds.SelectCommand = "C_MYSTORED_PROC" sds.ConnectionString = ConfigurationManager.ConnectionStrings("connstring").ConnectionString sds.SelectCommandType = SqlDataSourceCommandType.StoredProcedure Trace.Warn(String.Format("Parameters add start: {0} {1}", dpFrom.Text, dpTo.Text)) sds.SelectParameters.Add(New Parameter("FROMDATE", DbType.DateTime, dpFrom.Text)) sds.SelectParameters.Add(New Parameter("TODATE", DbType.DateTime, dpTo.Text)) Trace.Warn("Parameters add ended") Dim dv As DataView Dim dt As DataTable Trace.Warn("Trace 1") dv = sds.Select(New DataSourceSelectArguments()) Trace.Warn("Trace 2") If e IsNot Nothing Then dv.Sort = String.Format("{0} {1}", e.SortField, e.SortDirection) Trace.Warn("Trace 3") Else gvReport.CurrentSortColumnIndex = 0 gvReport.Columns(0).SortDirection = "DESC" Trace.Warn("Trace 4") End If Trace.Warn("Trace 5") dt = dv.ToTable() Cache("NewTenancyList") = dt Trace.Warn("Trace 6") Trace.Warn("About to databind") gvReport.DataSource = dt gvReport.DataBind() Trace.Warn("Databinded") What I don't understand and this is really weird, why does it work on my local machine but not on the live server? If i build the code on my local machine then copy over the complete \bin directory it works. If I pull the code from source safe, build then copy, I get this error. It seems to choke after the line "dv = sds.Select(New DataSourceSelectArguments())" in the code.

    Read the article

  • Web service occasionally slows down significantly

    - by Swoop
    My company is running into a problem with a web service that is written in C#/ASP.Net. The service receives an identity key for data in SQL Server and a path to generate and save a PDF report for this data. In most cases, this web service returns results to the calling web pages very quickly, usually within a few seconds max. However, it seems to occasionally hit a significant slowdown. The web application calling the web service will generate a timeout error when this slowdown occurs. We have checked and the PDF does get created and saved to the server, so it looks like the web service eventually finishes executing. It seems to take about 1 to 2 minutes for processing to have completed. The PDF is generated using ActiveReports from Data Dynamics. Wwhen this problem occurs, making a small change to the web service's config file (ie, adding a blank space to a connection string line) seems to restart the web service and everything is perfectly ok for a period of time afterwards. Other web applications that are running on the same web server do not seem to experience this type of behavior, only this particular web service. I have added the code for the web service below. It is basic calls to 3rd party libraries. We are not able to recreate this problem in test. I am wondering what might be causing this issue? [WebMethod] public string Publish(int identity, string transactionType, string directory, string filename) { try { AdpConnection Conn = new AdpConnection(ConfigurationManager.AppSettings["myDBConnString"]); AdpCommand Cmd = new AdpCommand("storedproc_GetData", oConn); AdpParameter Param; Cmd.CommandType = CommandType.StoredProcedure; Param = Cmd.CreateParameter("@Identity", DbType.Int32); Param.Value = identity; Cmd.Parameters.Add(oParam); Conn.Open(); string aResponse = Cmd.ExecuteScalar().ToString(); Conn.Close(); if (transactionType == "typeA") { //Parse response DataSet dsResponse = ParseDataResponse(aResponse); //dsResponse.WriteXml(@ConfigurationManager.AppSettings["DocsDir"] + identity.ToString() + ".xml"); DataDynamics.ActiveReports.ActiveReport3 rpt = new DataDynamics.ActiveReports.ActiveReport3(); rpt.LoadLayout(@ConfigurationManager.AppSettings["myReportPath"] + "TypeA.rpx"); rpt.AddNamedItem("ReportPath", @ConfigurationManager.AppSettings["myReportPath"]); rpt.AddNamedItem("XMLSTRING", FormatXML(dsResponse.GetXml())); DataDynamics.ActiveReports.DataSources.XMLDataSource xmlds = new DataDynamics.ActiveReports.DataSources.XMLDataSource(); xmlds.FileURL = null; xmlds.RecordsetPattern = "//DataPatternA"; xmlds.LoadXML(FormatXML(dsResponse.GetXml())); if (!System.IO.Directory.Exists(@ConfigurationManager.AppSettings["DocsDir"] + directory + @"\")) { System.IO.Directory.CreateDirectory(@ConfigurationManager.AppSettings["DocsDir"] + directory + @"\"); } string sXML = FormatXML(dsResponse.GetXml()); StreamWriter sw = new StreamWriter(@ConfigurationManager.AppSettings["DocsDir"] + directory + @"\" + filename + ".xml", false); sw.Write(sXML); sw.Close(); rpt.DataSource = xmlds; rpt.Run(true); DataDynamics.ActiveReports.Export.Pdf.PdfExport xPdf = new DataDynamics.ActiveReports.Export.Pdf.PdfExport(); xPdf.Export(rpt.Document, @ConfigurationManager.AppSettings["DocsDir"] + directory + @"\" + filename + ".pdf"); } } catch(Exception ex) { return "Error: " + ex.ToString(); } return @ConfigurationManager.AppSettings["DocsDir"] + directory + @"\" + filename + ".pdf"; }

    Read the article

  • Compress file to bytes for uploading to SQL Server

    - by Chris
    I am trying to zip files to an SQL Server database table. I can't ensure that the user of the tool has write priveledges on the source file folder so I want to load the file into memory, compress it to an array of bytes and insert it into my database. This below does not work. class ZipFileToSql { public event MessageHandler Message; protected virtual void OnMessage(string msg) { if (Message != null) { MessageHandlerEventArgs args = new MessageHandlerEventArgs(); args.Message = msg; Message(this, args); } } private int sourceFileId; private SqlConnection Conn; private string PathToFile; private bool isExecuting; public bool IsExecuting { get { return isExecuting; } } public int SourceFileId { get { return sourceFileId; } } public ZipFileToSql(string pathToFile, SqlConnection conn) { isExecuting = false; PathToFile = pathToFile; Conn = conn; } public void Execute() { isExecuting = true; byte[] data; byte[] cmpData; //create temp zip file OnMessage("Reading file to memory"); FileStream fs = File.OpenRead(PathToFile); data = new byte[fs.Length]; ReadWholeArray(fs, data); OnMessage("Zipping file to memory"); MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); cmpData = new byte[ms.Length]; ReadWholeArray(ms, cmpData); OnMessage("Saving file to database"); using (SqlCommand cmd = Conn.CreateCommand()) { cmd.CommandText = @"MergeFileUploads"; cmd.CommandType = CommandType.StoredProcedure; //cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = data; cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = cmpData; SqlParameter p = new SqlParameter(); p.ParameterName = "@SourceFileId"; p.Direction = ParameterDirection.Output; p.SqlDbType = SqlDbType.Int; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); sourceFileId = (int)p.Value; } OnMessage("File Saved"); isExecuting = false; } private void ReadWholeArray(Stream stream, byte[] data) { int offset = 0; int remaining = data.Length; float Step = data.Length / 100; float NextStep = data.Length - Step; while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; if (remaining < NextStep) { NextStep -= Step; } } } }

    Read the article

  • Problem while inserting data from GUI layer to database

    - by Rahul
    Hi all, I am facing problem while i am inserting new record from GUI part to database table. I have created database table Patient with id, name, age etc....id is identity primary key. My problem is while i am inserting duplicate name in table the control should go to else part, and display the message like...This name is already exits, pls try with another name... but in my coding not getting..... Here is all the code...pls somebody point me out whats wrong or how do this??? GUILayer: protected void BtnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; int intResult = 0; string name = TxtName.Text.Trim(); int age = Convert.ToInt32(TxtAge.Text); string gender; if (RadioButtonMale.Checked) { gender = RadioButtonMale.Text; } else { gender = RadioButtonFemale.Text; } string city = DropDownListCity.SelectedItem.Value; string typeofdisease = ""; foreach (ListItem li in CheckBoxListDisease.Items) { if (li.Selected) { typeofdisease += li.Value; } } typeofdisease = typeofdisease.TrimEnd(); PatientBAL PB = new PatientBAL(); PatientProperty obj = new PatientProperty(); obj.Name = name; obj.Age = age; obj.Gender = gender; obj.City = city; obj.TypeOFDisease = typeofdisease; try { intResult = PB.ADDPatient(obj); if (intResult > 0) { lblMessage.Text = "New record inserted successfully."; TxtName.Text = string.Empty; TxtAge.Text = string.Empty; RadioButtonMale.Enabled = false; RadioButtonFemale.Enabled = false; DropDownListCity.SelectedIndex = 0; CheckBoxListDisease.SelectedIndex = 0; } else { lblMessage.Text = "Name [<b>" + TxtName.Text + "</b>] alredy exists, try another name"; } } catch (Exception ex) { lblMessage.Text = ex.Message.ToString(); } finally { obj = null; PB = null; } } BAL layer: public class PatientBAL { public int ADDPatient(PatientProperty obj) { PatientDAL pdl = new PatientDAL(); try { return pdl.InsertData(obj); } catch { throw; } finally { pdl=null; } } } DAL layer: public class PatientDAL { public string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; public int InsertData(PatientProperty obj) { SqlConnection con = new SqlConnection(ConString); con.Open(); SqlCommand com = new SqlCommand("LoadData",con); com.CommandType = CommandType.StoredProcedure; try { com.Parameters.AddWithValue("@Name", obj.Name); com.Parameters.AddWithValue("@Age",obj.Age); com.Parameters.AddWithValue("@Gender",obj.Gender); com.Parameters.AddWithValue("@City", obj.City); com.Parameters.AddWithValue("@TypeOfDisease", obj.TypeOFDisease); return com.ExecuteNonQuery(); } catch { throw; } finally { com.Dispose(); con.Close(); } } } Property Class: public class PatientProperty { private string name; private int age; private string gender; private string city; private string typedisease; public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public string Gender { get { return gender; } set { gender = value; } } public string City { get { return city; } set { city = value; } } public string TypeOFDisease { get { return typedisease; } set { typedisease = value; } } } This is my stored Procedure: CREATE PROCEDURE LoadData ( @Name varchar(50), @Age int, @Gender char(10), @City char(10), @TypeofDisease varchar(50) ) as insert into Patient(Name, Age, Gender, City, TypeOfDisease)values(@Name,@Age, @Gender, @City, @TypeofDisease) GO

    Read the article

  • MVC using ODP.NET getting ORA-01840

    - by sse
    I am writing a simple MVC Application using ODP.NET. I am trying to call a Pl/Sql proc that inserts a record. Here is the simple Pl/Sql: procedure spAddCountry(pGisRecid in country.GISRECID%type, pCountryCode in country.COUNTRYCODE%type, pCountryName in country.COUNTRYNAME%type, pCurrencyCode in country.CURRENCYCODE%type, pEUTerritory in country.EUTERRITORY%type, pFatCAStatus in country.FATCASTATUS%type, pFATF in country.FATF%type, pFSCountryCode in country.COUNTRYCODE%type, pInsertedBy in country.INSERTEDBY%type, pInsertedOn in country.INSERTEDON%type, pLanguages in country.LANGUAGES%type, pNCCT in country.NCCT%type) is PRAGMA AUTONOMOUS_TRANSACTION; begin INSERT INTO COUNTRY (GISRECID, COUNTRYCODE, COUNTRYNAME, CURRENCYCODE, EUTERRITORY, FATCASTATUS, FATF, FSCOUNTRYCODE, INSERTEDBY, INSERTEDON, LANGUAGES, NCCT) VALUES(pGISRECID, pCOUNTRYCODE, pCOUNTRYNAME, pCURRENCYCODE, pEUTERRITORY, pFATCASTATUS, pFATF, pFSCOUNTRYCODE, pINSERTEDBY, pINSERTEDON, pLANGUAGES, pNCCT); Commit; end; I am having difficulty passing the date parameter, pInsertedOn, to the Stored Proc. I have verified that the web form retrieves the form data successfully and calls the AddCountry method below, which in turns calls the stored proc, spAddCountry, after populating all of the parms. Here is a snippet of the MVC C# code. I get the following exception: "ORA-01840 input value not long enough for date format". public void AddCountry(Country aCountry) //because the country object field names match the form field names they automatically get bound!! { string oradb = "Data Source=XYZ;User Id=XYZ;Password=xyz;"; OracleConnection conn = new OracleConnection(oradb); OracleCommand cmd = conn.CreateCommand(); cmd.CommandText = "tstpack.spAddCountry"; cmd.CommandType = CommandType.StoredProcedure; ... OracleParameter paramInsertedBy = new OracleParameter(); paramInsertedBy.ParameterName = "pInsertedBy"; paramInsertedBy.Value = aCountry.InsertedBy; cmd.Parameters.Add(paramInsertedBy); // CultureInfo ci = new CultureInfo("en-US"); OracleParameter paramInsertedOn = new OracleParameter(); paramInsertedOn.ParameterName = "pInsertedOn"; // paramInsertedOn.Value = DateTime.Now; //just testing to see if it's WebForm issue // paramInsertedOn.Value = Convert.ToDateTime(DateTime.Now.ToString(), ci); //flail! paramInsertedOn.Value = aCountry.InsertedOn; cmd.Parameters.Add(paramInsertedOn); ... conn.Open(); cmd.ExecuteNonQuery(); //CRASH! ORA-01840 conn.Close(); } Just to verify that the flow of the program is working, I tried removing the date parm "pInsertedOn" from the pl/sql and from the parm list above, and everything worked fine. I know I am going off of the rails with the date. Can someone tell me how to pass a date to Oracle from an MVC WebForm? Is there some sort of type cast needed? I would really appreciate an example too. Thanks so much! ps, I did try changing the parm type to Varchar2 in the Pl/Sql and doing some conversions myself in the Pl/Sql, the automatic MVC binder was getting in my way, forcing the property of paramInsertedOn.OracleType to DateTime. I tried forcing it to Varchar2, but no luck there either...

    Read the article

  • Value gets changed upon comiting. | CallableStatements

    - by Triztian
    Hello, I having a weird problem with a DAO class and a StoredProcedure, what is happening is that I use a CallableStatement object which takes 15 IN parameters, the value of the field id_color is retrieved correctly from the HTML forms it even is set up how it should in the CallableStatement setter methods, but the moment it is sent to the database the id_color is overwriten by the value 3 here's the "context": I have the following class DAO.CoverDAO which handles the CRUD operations of this table CREATE TABLE `cover_details` ( `refno` int(10) unsigned NOT NULL AUTO_INCREMENT, `shape` tinyint(3) unsigned NOT NULL , `id_color` tinyint(3) unsigned NOT NULL ', `reversefold` bit(1) NOT NULL DEFAULT b'0' , `x` decimal(6,3) unsigned NOT NULL , `y` decimal(6,3) unsigned NOT NULL DEFAULT '0.000', `typecut` varchar(10) NOT NULL, `cornershape` varchar(20) NOT NULL, `z` decimal(6,3) unsigned DEFAULT '0.000' , `othercornerradius` decimal(6,3) unsigned DEFAULT '0.000'', `skirt` decimal(5,3) unsigned NOT NULL DEFAULT '7.000', `foamTaper` varchar(3) NOT NULL, `foamDensity` decimal(2,1) unsigned NOT NULL , `straplocation` char(1) NOT NULL ', `straplength` decimal(6,3) unsigned NOT NULL, `strapinset` decimal(6,3) unsigned NOT NULL, `spayear` varchar(20) DEFAULT 'Not Specified', `spamake` varchar(20) DEFAULT 'Not Specified', `spabrand` varchar(20) DEFAULT 'Not Specified', PRIMARY KEY (`refno`) ) ENGINE=MyISAM AUTO_INCREMENT=143 DEFAULT CHARSET=latin1 $$ The the way covers are being inserted is by a stored procedure, which is the following: CREATE DEFINER=`root`@`%` PROCEDURE `putCover`( IN shape TINYINT, IN color TINYINT(3), IN reverse_fold BIT, IN x DECIMAL(6,3), IN y DECIMAL(6,3), IN type_cut VARCHAR(10), IN corner_shape VARCHAR(10), IN cutsize DECIMAL(6,3), IN corner_radius DECIMAL(6,3), IN skirt DECIMAL(5,3), IN foam_taper VARCHAR(7), IN foam_density DECIMAL(2,1), IN strap_location CHAR(1), IN strap_length DECIMAL(6,3), IN strap_inset DECIMAL(6,3) ) BEGIN INSERT INTO `dbre`.`cover_details` (`dbre`.`cover_details`.`shape`, `dbre`.`cover_details`.`id_color`, `dbre`.`cover_details`.`reversefold`, `dbre`.`cover_details`.`x`, `dbre`.`cover_details`.`y`, `dbre`.`cover_details`.`typecut`, `dbre`.`cover_details`.`cornershape`, `dbre`.`cover_details`.`z`, `dbre`.`cover_details`.`othercornerradius`, `dbre`.`cover_details`.`skirt`, `dbre`.`cover_details`.`foamTaper`, `dbre`.`cover_details`.`foamDensity`, `dbre`.`cover_details`.`strapLocation`, `dbre`.`cover_details`.`strapInset`, `dbre`.`cover_details`.`strapLength` ) VALUES (shape,color,reverse_fold, x,y,type_cut,corner_shape, cutsize,corner_radius,skirt,foam_taper,foam_density, strap_location,strap_inset,strap_length); END As you can see basically it just fills each field, now, the CoverDAO.create(CoverDTO cover) method which creates the cover is like so: public void create(CoverDTO cover) throws DAOException { Connection link = null; CallableStatement query = null; try { link = MySQL.getConnection(); link.setAutoCommit(false); query = link.prepareCall("{CALL putCover(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); query.setLong(1,cover.getShape()); query.setInt(2,cover.getColor()); query.setBoolean(3, cover.getReverseFold()); query.setBigDecimal(4,cover.getX()); query.setBigDecimal(5,cover.getY()); query.setString(6,cover.getTypeCut()); query.setString(7,cover.getCornerShape()); query.setBigDecimal(8, cover.getZ()); query.setBigDecimal(9, cover.getCornerRadius()); query.setBigDecimal(10, cover.getSkirt()); query.setString(11, cover.getFoamTaper()); query.setBigDecimal(12, cover.getFoamDensity()); query.setString(13, cover.getStrapLocation()); query.setBigDecimal(14, cover.getStrapLength()); query.setBigDecimal(15, cover.getStrapInset()); query.executeUpdate(); link.commit(); } catch (SQLException e) { throw new DAOException(e); } finally { close(link, query); } } The CoverDTO is made of accessesor methods, the MySQL object basically returns the connection from a pool. Here is the pset Query with dummy but appropriate data: putCover(1,10,0,80.000,80.000,'F','Cut',0.000,0,15.000,'4x2',1.5,'A',10.000,5.000) As you can see everything is fine just when I write to the DB instead of 10 in the second parameter a 3 is written. I have done the following: Traced the id_color value to the create method, still got replaced by a 3 Hardcoded the value in the DAO create method, still got replaced by a 3 Called the procedure from the MySQL Workbench, it worked fined so I assume something is happening in the create method, any help is really appreciated.

    Read the article

  • How to refresh DataGrid and DropDown on main page after hiding modal popup

    - by James
    Hi, I am adding records to a database from a modal popup. After hiding the modal popup, the page has not been refreshed even though I have Rebound the controls. I have reviewed a few postings on the web about this but the solution still evades me. I have attached my code after removing some of the extra detail... It seems I need to cause a postback but I don't know what needs to be changed. Some posts have talked about the extender being misplaced. Anyway, thank you James <asp:Content ID="Content1" ContentPlaceHolderID="Head" Runat="Server"> <div class="divBorder"> <asp:DataGrid id="dgrSessionFolders" runat="server" BorderWidth="2px" BorderStyle="Solid" BorderColor="#C0C0FF" Font-Names="Arial" Font-Bold="True" Font-Size="8pt" GridLines="Horizontal" AutoGenerateColumns="False" PageSize="9999" AllowPaging="False" OnItemCommand="dgrSessionFolders_Command" OnItemDataBound="CheckSessionFolderStatus" HorizontalAlign="Left" ForeColor="Blue" ShowFooter="True" CellPadding="2" OnSortCommand="dgrSessionFolders_Sort" AllowSorting="True"> </asp:DataGrid> </div> &nbsp;&nbsp;&nbsp; <asp:Label ID="Errormsg" runat="server" ForeColor="#CC0000"></asp:Label> <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline" ChildrenAsTriggers="false" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnEditTopic" /> <asp:AsyncPostBackTrigger ControlID="btnAdd" /> <asp:AsyncPostBackTrigger ControlID="btnUpdate" /> <asp:AsyncPostBackTrigger ControlID="btnDelete" /> <asp:AsyncPostBackTrigger ControlID="btnClear" /> <asp:AsyncPostBackTrigger ControlID="btnAddTopic" /> <asp:AsyncPostBackTrigger ControlID="btnUpdateTopic" /> <asp:AsyncPostBackTrigger ControlID="btnDeleteTopic" /> </Triggers> <ContentTemplate> <asp:panel id="pnl" runat="server" HorizontalAlign="Center" Height="48px" Width="100%" > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:ImageButton ID="btnEditTopic" runat="server" AlternateText="Edit Topic" ImageUrl="~/App_Themes/Common/images/BtnEditTopic.jpg" Height="28px"> </asp:ImageButton> <cc1:ModalPopupExtender ID="btnEditTopic_ModalPopupExtender" runat="server" BackgroundCssClass="modalBackground" DropShadow="true" Enabled="true" PopupControlID="pnlEditTopic" TargetControlID="btnEditTopicHidden" CancelControlID="btnEditTopicClose"> </cc1:ModalPopupExtender> <asp:ImageButton ID="btnAdd" runat="server" AlternateText="Add Folder" ImageUrl="~/App_Themes/Common/images/BtnAddFolder.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="btnUpdate" runat="server" AlternateText="Update Folder" ImageUrl="~/App_Themes/Common/images/BtnUpdateFolder.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="btnDelete" runat="server" AlternateText="Delete Folder" ImageUrl="~/App_Themes/Common/images/BtnDeleteFolder.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="BtnClear" runat="server" AlternateText="Clear Screen Input Fields" ImageUrl="~/App_Themes/Common/images/BtnAddMode.jpg" Height="28px"> </asp:ImageButton> <asp:Button ID="btnEditTopicHidden" runat="server" Enabled="false" Text="" Style="visibility: hidden" /> </asp:panel> <asp:Panel ID="pnlEditTopic" runat="server" CssClass="modalPopupEditTopic" Style="display: none;" > <table cellspacing="0" class="borderTable0" width="100%" style=""> <tr> <td colspan="10" class="Subhdr" align="center" style="width:100%"> <asp:label id="lblTopicScreenHdr" Cssclass="ScreenHdr" runat="server">Topic Maintenance</asp:label> </td> </tr> <tr> <td colspan="6"> <asp:Label ID="TopicPopErrorMsg" runat="server" ForeColor="#CC0000">&nbsp;</asp:Label> </td> </tr> <tr style="height:4px"> <td colspan="6" align="center"> <asp:ImageButton ID="btnAddTopic" runat="server" AlternateText="Add Topic" ImageUrl="~/App_Themes/Common/images/BtnApply.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="btnUpdateTopic" runat="server" AlternateText="Update Topic" ImageUrl="~/App_Themes/Common/images/BtnApply.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="btnDeleteTopic" runat="server" AlternateText="Delete Topic" ImageUrl="~/App_Themes/Common/images/BtnDelete.jpg" Height="28px"> </asp:ImageButton> <asp:ImageButton ID="btnEditTopicClose" runat="server" AlternateText="Close Edit Topic Popup" ImageUrl="~/App_Themes/Common/images/BtnCancel.jpg" Height="28px"> </asp:ImageButton> </td> </tr> </table> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> Private Sub btnAddTopic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddTopic.Click 'Add the Topic table entry AddTopic() 'Display an informational message Errormsg.Text = "The Topic has been successfully added, thank you! " Errormsg.ForeColor = Drawing.Color.Blue 'Rebind the Topic Drop Down and set to added Topic ddlSessionTopic.DataBind() ddlSessionTopic.SelectedValue = drTopic("TOPC_ID") 'Rebind the Session Folders grid RebindGrid() 'Hide the Topic Popup btnEditTopic_ModalPopupExtender.Hide() End Sub Private Sub RebindGrid() cnnSQL = New SqlConnection(strConnection) cmdSQL = New SqlCommand("GetSessionFoldersForGrid", cnnSQL) cmdSQL.CommandType = CommandType.StoredProcedure cmdSQL.Parameters.Clear() cnnSQL.Open() dadSQL = New SqlDataAdapter(cmdSQL) dadSQL.SelectCommand = cmdSQL dadSQL.Fill(dtSessionFolderGrid) cnnSQL.Close() dvSessionFolderGrid = dtSessionFolderGrid.DefaultView dvSessionFolderGrid.Sort = String.Format("{0} {1}{2}", so.Sortfield, so.SortDirection, so.SortSuffix) dgrSessionFolders.DataSource = dvSessionFolderGrid dgrSessionFolders.DataBind() End Sub

    Read the article

  • inserting null values in datetime column and integer column

    - by reggie
    I am using C# and developing a winform application. I have a project class which has the project attributes. the constructor of the project class is as follows: newProject = new Project(GCD_ID.IsNull() ? (int?)null : Convert.ToInt32(GCD_ID), txt_Proj_Desc.Text, txt_Prop_Name.Text, ST.ID.ToString().IsNull() ? null: ST.ID.ToString(), cmbCentre.Text, SEC.ID.ToString().IsNull() ? null : SEC.ID.ToString(), cmbZone.Text, FD.ID.ToString().IsNull() ? null : FD.ID.ToString(), DT.ID.ToString().IsNull() ? null : DT.ID.ToString(), OP.ID.ToString().IsNull() ? null : OP.ID.ToString(), T.ID.ToString().IsNull() ? null : T.ID.ToString(), CKV.ID.ToString().IsNull() ? null : CKV.ID.ToString(), STAT.ID.ToString().IsNull() ? null : STAT.ID.ToString(), MW.IsNull() ? (Double?)null : Convert.ToDouble(MW), txt_Subject.Text, Ip_Num.IsNull() ? (int?)null : Convert.ToInt32(Ip_Num), H1N_ID.IsNull() ? (int?)null : Convert.ToInt32(H1N_ID), NOMS_Slip_Num.IsNull() ? (int?)null : Convert.ToInt32(NOMS_Slip_Num), NMS_Updated.IsNull() ? (DateTime?)null : Convert.ToDateTime(NMS_Updated), Received_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Received_Date), Actual_IS_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Actual_IS_Date), Scheduled_IS_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Scheduled_IS_Date), UpSt.ID.ToString().IsNull() ? null : UpSt.ID.ToString(), UpFd.ID.ToString().IsNull() ? null : UpFd.ID.ToString(), txtHVCircuit.Text, cmbbxSIA.Text); My problem is that i cannot insert values into the database when the datetime variables and the integer variables are null. all this data are assigned to the variable from textboxes on the form.. bELOW is the database function which takes in all the variables and insert them into the database. public static void createNewProject(int? GCD_ID, string Project_Desc, string Proponent_Name, int Station_ID, string OpCentre, int Sector_ID, string PLZone, int Feeder, int DxTx_ID, int OpControl_ID, int Type_ID, int ConnKV_ID, int Status_ID, double? MW, string Subject, int? Ip_Num, int? H1N_ID, int? NOMS_Slip_Num, DateTime? NMS_Updated, DateTime? Received_Date, DateTime? Actual_IS_Date, DateTime? Scheduled_IS_Date, int UP_Station_ID, int UP_Feeder_ID, string @HV_Circuit, string SIA_Required) { SqlConnection conn = null; try { //Takes in all the employee details to be added to the database. conn = new SqlConnection(databaseConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("createNewProject", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("GCD_ID", GCD_ID)); cmd.Parameters.Add(new SqlParameter("Project_Desc", MiscFunctions.Capitalize(Project_Desc))); cmd.Parameters.Add(new SqlParameter("Proponent_Name", MiscFunctions.Capitalize(Proponent_Name))); cmd.Parameters.Add(new SqlParameter("Station_ID", Station_ID)); cmd.Parameters.Add(new SqlParameter("OpCentre", OpCentre)); cmd.Parameters.Add(new SqlParameter("Sector_ID", Sector_ID)); cmd.Parameters.Add(new SqlParameter("PLZone", PLZone)); cmd.Parameters.Add(new SqlParameter("Feeder", Feeder)); cmd.Parameters.Add(new SqlParameter("DxTx_ID", DxTx_ID)); cmd.Parameters.Add(new SqlParameter("OpControl_ID", OpControl_ID)); cmd.Parameters.Add(new SqlParameter("Type_ID", Type_ID)); cmd.Parameters.Add(new SqlParameter("ConnKV_ID", ConnKV_ID)); cmd.Parameters.Add(new SqlParameter("Status_ID", Status_ID)); cmd.Parameters.Add(new SqlParameter("MW", MW)); cmd.Parameters.Add(new SqlParameter("Subject", Subject)); cmd.Parameters.Add(new SqlParameter("Ip_Num", Ip_Num)); cmd.Parameters.Add(new SqlParameter("H1N_ID", H1N_ID)); cmd.Parameters.Add(new SqlParameter("NOMS_Slip_Num", NOMS_Slip_Num)); cmd.Parameters.Add(new SqlParameter("NMS_Updated", NMS_Updated)); cmd.Parameters.Add(new SqlParameter("Received_Date", Received_Date)); cmd.Parameters.Add(new SqlParameter("Actual_IS_Date", Actual_IS_Date)); cmd.Parameters.Add(new SqlParameter("Scheduled_IS_Date", Scheduled_IS_Date)); cmd.Parameters.Add(new SqlParameter("UP_Station_ID", UP_Station_ID)); cmd.Parameters.Add(new SqlParameter("UP_Feeder_ID", UP_Feeder_ID)); cmd.Parameters.Add(new SqlParameter("HV_Circuit", HV_Circuit)); cmd.Parameters.Add(new SqlParameter("SIA_Required", SIA_Required)); cmd.ExecuteNonQuery(); } catch (Exception e) //returns if error incurred. { MessageBox.Show("Error occured in createNewProject" + Environment.NewLine + e.ToString()); } finally { if (conn != null) { conn.Close(); } } } My question is, how do i insert values into the database. please please help

    Read the article

  • unable to update gridview

    - by bhakti
    Please help ,i have added update/edit command button in gridview so to update data in my sql server database but am unable to do it. Data is not updated in database . ======code for onrowupdate======================================== protected void gRowUpdate(object sender, GridViewUpdateEventArgs e) { Books b = null; b = new Books(); DataTable dt=null; GridView g = (GridView)sender; try { dt=new DataTable(); b = new Books(); b.author = Convert.ToString(g.Rows[e.RowIndex].FindControl("Author")); b.bookID = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("BookID")); b.title = Convert.ToString(g.Rows[e.RowIndex].FindControl("Title")); b.price = Convert.ToDouble(g.Rows[e.RowIndex].FindControl("Price")); // b.rec = Convert.ToString(g.Rows[e.RowIndex].FindControl("Date_of_reciept")); b.ed = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.bill = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.cre_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.src = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.pages = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("Edition")); b.pub = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.mod_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.remark = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); // b.year = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.updatebook(b); g.EditIndex = -1; dt = b.GetAllBooks(); g.DataSource = dt; g.DataBind(); } catch (Exception ex) { throw (ex); } finally { b = null; } } ===================My stored procedure for update book able to update database by exec in sqlserver mgmt studio========================== set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[usp_updatebook] @bookid bigint, @author varchar(50), @title varchar(50), @price bigint, @src_equisition varchar(50), @bill_no varchar(50), @publisher varchar(50), @pages bigint, @remark varchar(50), @edition varchar(50), @created_by varchar(50), @modified_by varchar(50) /*@date_of_reciept datetime, @year_of_publication datetime*/ AS declare @modified_on datetime set @modified_on=getdate() UPDATE books SET author=@author, title=@title, price=@price, src_equisition=@src_equisition, bill_no=@bill_no, publisher=@publisher, /*Date_of_reciept=@date_of_reciept,*/ pages=@pages, remark=@remark, edition=@edition, /*Year_of_publication=@year_of_publication,*/ created_by=@created_by, modified_on=@modified_on, modified_by=@modified_by WHERE bookid=@bookid ========================class library function for update==================== public void updatebook(Books b) { DataAccess dbAccess = null; SqlCommand cmd = null; try { dbAccess = new DataAccess(); cmd = dbAccess.GetSQLCommand("usp_updatebook", CommandType.StoredProcedure); cmd.Parameters.Add("@bookid", SqlDbType.VarChar, 50).Value = b.bookID; cmd.Parameters.Add("@author", SqlDbType.VarChar, 50).Value = b.author; cmd.Parameters.Add("@title", SqlDbType.VarChar, 50).Value = b.title; cmd.Parameters.Add("@price", SqlDbType.Money).Value = b.price; cmd.Parameters.Add("@publisher", SqlDbType.VarChar, 50).Value = b.pub; // cmd.Parameters.Add("@year_of_publication", SqlDbType.DateTime).Value =Convert.ToDateTime( b.year); cmd.Parameters.Add("@src_equisition", SqlDbType.VarChar, 50).Value = b.src; cmd.Parameters.Add("@bill_no", SqlDbType.VarChar, 50).Value = b.bill; cmd.Parameters.Add("@remark", SqlDbType.VarChar, 50).Value = b.remark; cmd.Parameters.Add("@pages", SqlDbType.Int).Value = b.pages; cmd.Parameters.Add("@edition", SqlDbType.VarChar, 50).Value = b.ed; // cmd.Parameters.Add("@date_of_reciept", SqlDbType.DateTime).Value = Convert.ToDateTime(b.rec); // cmd.Parameters.Add("@created_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.cre_on); cmd.Parameters.Add("@created_by", SqlDbType.VarChar, 50).Value = b.cre_by; //cmd.Parameters.Add("@modified_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.mod_on); cmd.Parameters.Add("@modified_by", SqlDbType.VarChar, 50).Value = b.mod_by; cmd.ExecuteNonQuery(); } catch (Exception ex) { throw (ex); } finally { if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close(); dbAccess = null; cmd = null; } } I have also tried to do update by following way protected void gv1_updating(object sender, GridViewUpdateEventArgs e) { GridView g = (GridView)sender; abc a = new abc(); DataTable dt = new DataTable(); try { a.cd_Id = Convert.ToInt32(g.DataKeys[e.RowIndex].Values[0].ToString()); //TextBox b = (TextBox)g.Rows[e.RowIndex].Cells[0].FindControl("cd_id"); TextBox c = (TextBox)g.Rows[e.RowIndex].Cells[2].FindControl("cd_name"); TextBox d = (TextBox)g.Rows[e.RowIndex].Cells[3].FindControl("version"); TextBox f = (TextBox)g.Rows[e.RowIndex].Cells[4].FindControl("company"); TextBox h = (TextBox)g.Rows[e.RowIndex].Cells[6].FindControl("created_by"); TextBox i = (TextBox)g.Rows[e.RowIndex].Cells[8].FindControl("modified_by"); //a.cd_Id = Convert.ToInt32(b.Text); a.cd_name = c.Text; a.ver = d.Text; a.comp = f.Text; a.cre_by = h.Text; a.mod_by = i.Text; a.updateDigi(a); g.EditIndex = -1; dt = a.GetAllDigi(); g.DataSource = dt; g.DataBind(); } catch(Exception ex) { throw (ex); } finally { dt = null; a = null; g = null; } } =================== but have error of Index out of range exception========= please do reply,thanxs in advance

    Read the article

  • Click edit button twice in gridview asp.net c# issue

    - by Supriyo Banerjee
    I have a gridview created on a page where I want to provide an edit button for the user to click in. However the issue is the grid view row becomes editable only while clicking the edit button second time. Not sure what is going wrong here, any help would be appreciated. One additional point is my grid view is displayed on the page only on a click of a button and is not there on page_load event hence. Posting the code snippets: //MY Aspx code <Columns> <asp:TemplateField HeaderText="Slice" SortExpression="name"> <ItemTemplate> <asp:Label ID="lblslice" Text='<%# Eval("slice") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblslice" Text='<%# Eval("slice") %>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Metric" SortExpression="Description"> <ItemTemplate> <asp:Label ID="lblmetric" Text='<%# Eval("metric")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblmetric" Text='<%# Eval("metric")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Original" SortExpression="Type"> <ItemTemplate> <asp:Label ID="lbloriginal" Text='<%# Eval("Original")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lbloriginal" Text='<%# Eval("Original")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="WOW" SortExpression="Market"> <ItemTemplate> <asp:Label ID="lblwow" Text='<%# Eval("WOW")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblwow" Text='<%# Eval("WOW")%>' runat="server"></asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Change" SortExpression="Market" > <ItemTemplate> <asp:Label ID="lblChange" Text='<%# Eval("Change")%>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="TxtCustomerID" Text='<%# Eval("Change") %> ' runat="server"></asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="Edit" ShowEditButton="True" /> </Columns> </asp:GridView> //My code behind: protected void Page_Load(object sender, EventArgs e) { } public void populagridview1(string slice,string fromdate,string todate,string year) { SqlCommand cmd; SqlDataAdapter da; DataSet ds; cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "usp_geteventchanges"; cmd.Connection = conn; conn.Open(); SqlParameter param1 = new SqlParameter("@slice", slice); cmd.Parameters.Add(param1); SqlParameter param2 = new SqlParameter("@fromdate", fromdate); cmd.Parameters.Add(param2); SqlParameter param3 = new SqlParameter("@todate", todate); cmd.Parameters.Add(param3); SqlParameter param4 = new SqlParameter("@year", year); cmd.Parameters.Add(param4); da = new SqlDataAdapter(cmd); ds = new DataSet(); da.Fill(ds, "Table"); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } protected void ImpactCalc(object sender, EventArgs e) { populagridview1(ddl_slice.SelectedValue, dt_to_integer(Picker1.Text), dt_to_integer(Picker2.Text), Txt_Year.Text); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { gvEditIndex = e.NewEditIndex; Gridview1.DataBind(); } My page layout This edit screen appears after clicking edit twice.. the grid view gets displayed on hitting the Calculate impact button. The data is from a backend stored procedure which is fired on clicking the Calculate impact button

    Read the article

  • does log4net AdoNetAppender support sql server 2008?

    - by schrodinger's code
    my config file below: very strange, i have spent a day to find out where i am wrong, but still not working, it still not log anything in the database,but i can output them using RollingFileAppender. Also, the store procedure WriteLog is working well.(I have tested it using sql server studio). I have tried to change the connectionType but not working. Unfortunately I dont have sql server 2000/2005 to test, my log4net version should be the latest one: log4net 1.2.10. Any help is appreciated. <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender"> <!--<threshold value="OFF" />--> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <!--<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />--> <connectionString value="Data Source=.\MSSQLSERVER2008,2222;Initial Catalog=UnleashedSaaS;User ID=sa;Password=dogblack;" /> <commandType value="StoredProcedure" /> <commandText value="WriteLog" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout" value="%thread" /> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout" value="%level" /> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout" value="%logger" /> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout" value="%message" /> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" > <!--<threshold value="OFF" />--> <file value="LogData\\" /> <appendToFile value="true" /> <datePattern value="ul_yyyy-MM-dd.LOG" /> <maxSizeRollBackups value="10" /> <rollingStyle value="Date" /> <maximumFileSize value="2MB" /> <staticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %u %c %l %m %n%n%n" /> </layout> </appender> <root> <level value="ALL"/> <appender-ref ref="AdoNetAppender_SqlServer" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>

    Read the article

  • STORED PROCEDURE working in my local test machine cannot be created in production environment.

    - by Marcos Buarque
    Hi, I have an SQL CREATE PROCEDURE statement that runs perfectly in my local SQL Server, but cannot be recreated in production environment. The error message I get in production is Msg 102, Level 15, State 1, Incorrect syntax near '='. It is a pretty big query and I don't want to annoy StackOverflow users, but I simply can't find a solution. If only you could point me out what settings I could check in the production server in order to enable running the code... I must be using some kind of syntax or something that is conflicting with some setting in production. This PROCEDURE was already registered in production before, but when I ran a DROP - CREATE PROCEDURE today, the server was able to drop the procedure, but not to recreate it. I will paste the code below. Thank you! =============== USE [Enorway] GO /****** Object: StoredProcedure [dbo].[Spel_CM_ChartsUsersTotals] Script Date: 03/17/2010 11:59:57 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROC [dbo].[Spel_CM_ChartsUsersTotals] @IdGroup int, @IdAssessment int, @UserId int AS SET NOCOUNT ON DECLARE @RequiredColor varchar(6) SET @RequiredColor = '3333cc' DECLARE @ManagersColor varchar(6) SET @ManagersColor = '993300' DECLARE @GroupColor varchar(6) SET @GroupColor = 'ff0000' DECLARE @SelfColor varchar(6) SET @SelfColor = '336600' DECLARE @TeamColor varchar(6) SET @TeamColor = '993399' DECLARE @intMyCounter tinyint DECLARE @intManagersPosition tinyint DECLARE @intGroupPosition tinyint DECLARE @intSelfPosition tinyint DECLARE @intTeamPosition tinyint SET @intMyCounter = 1 -- Table that will hold the subtotals... DECLARE @tblTotalsSource table ( IdCompetency int, CompetencyName nvarchar(200), FunctionRequiredLevel float, ManagersAverageAssessment float, SelfAssessment float, GroupAverageAssessment float, TeamAverageAssessment float ) INSERT INTO @tblTotalsSource ( IdCompetency, CompetencyName, FunctionRequiredLevel, ManagersAverageAssessment, SelfAssessment, GroupAverageAssessment, TeamAverageAssessment ) SELECT e.[IdCompetency], dbo.replaceAccentChar(e.[Name]) AS CompetencyName, (i.[LevelNumber]) AS FunctionRequiredLevel, ( SELECT ROUND(avg(CAST(ac.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData aa INNER JOIN Spel_CM_CompetenciesLevels ab ON aa.[IdCompetencyLevel] = ab.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels ac ON ab.[IdLevel] = ac.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents ad ON aa.[IdAssessmentEvent] = ad.[IdAssessmentEvent] WHERE aa.[EvaluatedUserId] = @UserId AND aa.[AssessmentType] = 't' AND aa.[IdGroup] = @IdGroup AND ab.[IdCompetency] = e.[IdCompetency] AND ad.[IdAssessment] = @IdAssessment ) AS ManagersAverageAssessment, ( SELECT bc.[LevelNumber] FROM Spel_CM_AssessmentsData ba INNER JOIN Spel_CM_CompetenciesLevels bb ON ba.[IdCompetencyLevel] = bb.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels bc ON bb.[IdLevel] = bc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents bd ON ba.[IdAssessmentEvent] = bd.[IdAssessmentEvent] WHERE ba.[EvaluatedUserId] = @UserId AND ba.[AssessmentType] = 's' AND ba.[IdGroup] = @IdGroup AND bb.[IdCompetency] = e.[IdCompetency] AND bd.[IdAssessment] = @IdAssessment ) AS SelfAssessment, ( SELECT ROUND(avg(CAST(cc.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData ca INNER JOIN Spel_CM_CompetenciesLevels cb ON ca.[IdCompetencyLevel] = cb.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels cc ON cb.[IdLevel] = cc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents cd ON ca.[IdAssessmentEvent] = cd.[IdAssessmentEvent] WHERE ca.[EvaluatedUserId] = @UserId AND ca.[AssessmentType] = 'g' AND ca.[IdGroup] = @IdGroup AND cb.[IdCompetency] = e.[IdCompetency] AND cd.[IdAssessment] = @IdAssessment ) AS GroupAverageAssessment, ( SELECT ROUND(avg(CAST(dc.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData da INNER JOIN Spel_CM_CompetenciesLevels db ON da.[IdCompetencyLevel] = db.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels dc ON db.[IdLevel] = dc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents dd ON da.[IdAssessmentEvent] = dd.[IdAssessmentEvent] WHERE da.[EvaluatedUserId] = @UserId AND da.[AssessmentType] = 'm' AND da.[IdGroup] = @IdGroup AND db.[IdCompetency] = e.[IdCompetency] AND dd.[IdAssessment] = @IdAssessment ) AS TeamAverageAssessment FROM Spel_CM_AssessmentsData a INNER JOIN Spel_CM_AssessmentsEvents c ON a.[IdAssessmentEvent] = c.[IdAssessmentEvent] INNER JOIN Spel_CM_CompetenciesLevels d ON a.[IdCompetencyLevel] = d.[IdCompetencyLevel] INNER JOIN Spel_CM_Competencies e ON d.[IdCompetency] = e.[IdCompetency] INNER JOIN Spel_CM_Levels f ON d.[IdLevel] = f.[IdLevel] -- This will link with user's assigned functions INNER JOIN Spel_CM_FunctionsCompetenciesLevels g ON a.[IdFunction] = g.[IdFunction] INNER JOIN Spel_CM_CompetenciesLevels h ON g.[IdCompetencyLevel] = h.[IdCompetencyLevel] AND e.[IdCompetency] = h.[IdCompetency] INNER JOIN Spel_CM_Levels i ON h.[IdLevel] = i.[IdLevel] WHERE (NOT c.[EndDate] IS NULL) AND a.[EvaluatedUserId] = @UserId AND c.[IdAssessment] = @IdAssessment AND a.[IdGroup] = @IdGroup GROUP BY e.[IdCompetency], e.[Name], i.[LevelNumber] ORDER BY e.[Name] ASC -- This will define the position of each element (managers, group, self and team) SELECT @intManagersPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT ManagersAverageAssessment IS NULL IF IsNumeric(@intManagersPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intGroupPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT GroupAverageAssessment IS NULL IF IsNumeric(@intGroupPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intSelfPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT SelfAssessment IS NULL IF IsNumeric(@intSelfPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intTeamPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT TeamAverageAssessment IS NULL -- This will render the final table for the end user. The tabe will flatten some of the numbers to allow them to be prepared for Google Graphics. SELECT SUBSTRING( ( SELECT ( '|' + REPLACE(ma.[CompetencyName],' ','+')) FROM @tblTotalsSource ma ORDER BY ma.[CompetencyName] DESC FOR XML PATH('') ), 2, 1000) AS 'CompetenciesNames', SUBSTRING( ( SELECT ( ',' + REPLACE(ra.[FunctionRequiredLevel]*10,' ','+')) FROM @tblTotalsSource ra FOR XML PATH('') ), 2, 1000) AS 'FunctionRequiredLevel', SUBSTRING( ( SELECT ( ',' + CAST(na.[ManagersAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource na FOR XML PATH('') ), 2, 1000) AS 'ManagersAverageAssessment', SUBSTRING( ( SELECT ( ',' + CAST(oa.[GroupAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource oa FOR XML PATH('') ), 2, 1000) AS 'GroupAverageAssessment', SUBSTRING( ( SELECT ( ',' + CAST(pa.[SelfAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource pa FOR XML PATH('') ), 2, 1000) AS 'SelfAssessment', SUBSTRING( ( SELECT ( ',' + CAST(qa.[TeamAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource qa FOR XML PATH('') ), 2, 1000) AS 'TeamAverageAssessment', SUBSTRING( ( SELECT ( '|t++' + CAST([FunctionRequiredLevel] AS varchar(10)) + ',' + @RequiredColor + ',0,' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'FunctionRequiredAverageLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([ManagersAverageAssessment] AS varchar(10)) + ',' + @ManagersColor + ',' + CAST(@intManagersPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'ManagersLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([GroupAverageAssessment] AS varchar(10)) + ',' + @GroupColor + ',' + CAST(@intGroupPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'GroupLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([SelfAssessment] AS varchar(10)) + ',' + @SelfColor + ',' + CAST(@intSelfPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'SelfLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([TeamAverageAssessment] AS varchar(10)) + ',' + @TeamColor + ',' + CAST(@intTeamPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',10') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'TeamLabel', (Count(src.[IdCompetency]) * 30) + 100 AS 'ControlHeight' FROM @tblTotalsSource src SET NOCOUNT OFF GO

    Read the article

  • Fastest way to move records from a oracle DB into MS sql server after processing

    - by user347748
    Hi.. Ok this is the scenario...I have a table in Oracle that acts like a queue... A VB.net program reads the queue and calls a stored proc in MS SQL Server that processes and then inserts the message into another SQL server table and then deletes the record from the oracle table. We use a datareader to read the records from Oracle and then call the stored proc for each of the records. The program seems to be a little slow. The stored procedure itself isnt slow. The SP by itself when called in a loop can process about 2000 records in 20 seconds. BUt when called from the .Net program, the execution time is about 5 records per second. I have seen that most of the time consumed is in calling the stored procedure and waiting for it to return. Is there a better way of doing this? Here is a snippet of the actual code Function StartDataXfer() As Boolean Dim status As Boolean = False Try SqlConn.Open() OraConn.Open() c.ErrorLog(Now.ToString & "--Going to Get the messages from oracle", 1) If GetMsgsFromOracle() Then c.ErrorLog(Now.ToString & "--Got messages from oracle", 1) If ProcessMessages() Then c.ErrorLog(Now.ToString & "--Finished Processing all messages in the queue", 0) status = True Else c.ErrorLog(Now.ToString & "--Failed to Process all messages in the queue", 0) status = False End If Else status = True End If StartDataXfer = status Catch ex As Exception Finally SqlConn.Close() OraConn.Close() End Try End Function Private Function GetMsgsFromOracle() As Boolean Try OraDataAdapter = New OleDb.OleDbDataAdapter OraDataTable = New System.Data.DataTable OraSelCmd = New OleDb.OleDbCommand GetMsgsFromOracle = False With OraSelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = GetMsgSql End With OraDataAdapter.SelectCommand = OraSelCmd OraDataAdapter.Fill(OraDataTable) If OraDataTable.Rows.Count > 0 Then GetMsgsFromOracle = True End If Catch ex As Exception GetMsgsFromOracle = False End Try End Function Private Function ProcessMessages() As Boolean Try ProcessMessages = False PrepareSQLInsert() PrepOraDel() i = 0 Dim Method As Integer Dim OraDataRow As DataRow c.ErrorLog(Now.ToString & "--Going to call message sending procedure", 2) For Each OraDataRow In OraDataTable.Rows With OraDataRow Method = GetMethod(.Item(0)) SQLInsCmd.Parameters("RelLifeTime").Value = c.RelLifetime SQLInsCmd.Parameters("Param1").Value = Nothing SQLInsCmd.Parameters("ID").Value = GenerateTransactionID() ' Nothing SQLInsCmd.Parameters("UID").Value = Nothing SQLInsCmd.Parameters("Param").Value = Nothing SQLInsCmd.Parameters("Credit").Value = 0 SQLInsCmd.ExecuteNonQuery() 'check the return value If SQLInsCmd.Parameters("ReturnValue").Value = 1 And SQLInsCmd.Parameters("OutPutParam").Value = 0 Then 'success 'delete the input record from the source table once it is logged c.ErrorLog(Now.ToString & "--Moved record successfully", 2) OraDataAdapter.DeleteCommand.Parameters("P(0)").Value = OraDataRow.Item(6) OraDataAdapter.DeleteCommand.ExecuteNonQuery() c.ErrorLog(Now.ToString & "--Deleted record successfully", 2) OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Committed record successfully", 2) i = i + 1 Else 'failure c.ErrorLog(Now.ToString & "--Failed to exec: " & c.DestIns & "Status: " & SQLInsCmd.Parameters("OutPutParam").Value & " and TrackId: " & SQLInsCmd.Parameters("TrackID").Value.ToString, 0) End If If File.Exists("stop.txt") Then c.ErrorLog(Now.ToString & "--Stop File Found", 1) 'ProcessMessages = True 'Exit Function Exit For End If End With Next OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Updated Oracle Table", 1) c.ErrorLog(Now.ToString & "--Moved " & i & " records from Oracle to SQL Table", 1) ProcessMessages = True Catch ex As Exception ProcessMessages = False c.ErrorLog(Now.ToString & "--MoveMsgsToSQL: " & ex.Message, 0) Finally OraDataTable.Clear() OraDataTable.Dispose() OraDataAdapter.Dispose() OraDelCmd.Dispose() OraDelCmd = Nothing OraSelCmd = Nothing OraDataTable = Nothing OraDataAdapter = Nothing End Try End Function Public Function GenerateTransactionID() As Int64 Dim SeqNo As Int64 Dim qry As String Dim SqlTransCmd As New OleDb.OleDbCommand qry = " select seqno from StoreSeqNo" SqlTransCmd.CommandType = CommandType.Text SqlTransCmd.Connection = SqlConn SqlTransCmd.CommandText = qry SeqNo = SqlTransCmd.ExecuteScalar If SeqNo > 2147483647 Then qry = "update StoreSeqNo set seqno=1" SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = 1 Else qry = "update StoreSeqNo set seqno=" & SeqNo + 1 SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = SeqNo End If End Function Private Function PrepareSQLInsert() As Boolean 'function to prepare the insert statement for the insert into the SQL stmt using 'the sql procedure SMSProcessAndDispatch Try Dim dr As DataRow SQLInsCmd = New OleDb.OleDbCommand With SQLInsCmd .CommandType = CommandType.StoredProcedure .Connection = SqlConn .CommandText = SQLInsProc .Parameters.Add("ReturnValue", OleDb.OleDbType.Integer) .Parameters("ReturnValue").Direction = ParameterDirection.ReturnValue .Parameters.Add("OutPutParam", OleDb.OleDbType.Integer) .Parameters("OutPutParam").Direction = ParameterDirection.Output .Parameters.Add("TrackID", OleDb.OleDbType.VarChar, 70) .Parameters.Add("RelLifeTime", OleDb.OleDbType.TinyInt) .Parameters("RelLifeTime").Direction = ParameterDirection.Input .Parameters.Add("Param1", OleDb.OleDbType.VarChar, 160) .Parameters("Param1").Direction = ParameterDirection.Input .Parameters.Add("TransID", OleDb.OleDbType.VarChar, 70) .Parameters("TransID").Direction = ParameterDirection.Input .Parameters.Add("UID", OleDb.OleDbType.VarChar, 20) .Parameters("UID").Direction = ParameterDirection.Input .Parameters.Add("Param", OleDb.OleDbType.VarChar, 160) .Parameters("Param").Direction = ParameterDirection.Input .Parameters.Add("CheckCredit", OleDb.OleDbType.Integer) .Parameters("CheckCredit").Direction = ParameterDirection.Input .Prepare() End With Catch ex As Exception c.ErrorLog(Now.ToString & "--PrepareSQLInsert: " & ex.Message) End Try End Function Private Function PrepOraDel() As Boolean OraDelCmd = New OleDb.OleDbCommand Try PrepOraDel = False With OraDelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = DelSrcSQL .Parameters.Add("P(0)", OleDb.OleDbType.VarChar, 160) 'RowID .Parameters("P(0)").Direction = ParameterDirection.Input .Prepare() End With OraDataAdapter.DeleteCommand = OraDelCmd PrepOraDel = True Catch ex As Exception PrepOraDel = False End Try End Function WHat i would like to know is, if there is anyway to speed up this program? Any ideas/suggestions would be highly appreciated... Regardss, Chetan

    Read the article

  • Fastest way to move records from an Oracle database into SQL Server

    - by user347748
    Ok this is the scenario... I have a table in Oracle that acts like a queue... A VB.net program reads the queue and calls a stored proc in SQL Server that processes and then inserts the message into another SQL Server table and then deletes the record from the oracle table. We use a DataReader to read the records from Oracle and then call the stored proc for each of the records. The program seems to be a little slow. The stored procedure itself isn't slow. The SP by itself when called in a loop can process about 2000 records in 20 seconds. But when called from the .Net program, the execution time is about 5 records per second. I have seen that most of the time consumed is in calling the stored procedure and waiting for it to return. Is there a better way of doing this? Here is a snippet of the actual code Function StartDataXfer() As Boolean Dim status As Boolean = False Try SqlConn.Open() OraConn.Open() c.ErrorLog(Now.ToString & "--Going to Get the messages from oracle", 1) If GetMsgsFromOracle() Then c.ErrorLog(Now.ToString & "--Got messages from oracle", 1) If ProcessMessages() Then c.ErrorLog(Now.ToString & "--Finished Processing all messages in the queue", 0) status = True Else c.ErrorLog(Now.ToString & "--Failed to Process all messages in the queue", 0) status = False End If Else status = True End If StartDataXfer = status Catch ex As Exception Finally SqlConn.Close() OraConn.Close() End Try End Function Private Function GetMsgsFromOracle() As Boolean Try OraDataAdapter = New OleDb.OleDbDataAdapter OraDataTable = New System.Data.DataTable OraSelCmd = New OleDb.OleDbCommand GetMsgsFromOracle = False With OraSelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = GetMsgSql End With OraDataAdapter.SelectCommand = OraSelCmd OraDataAdapter.Fill(OraDataTable) If OraDataTable.Rows.Count > 0 Then GetMsgsFromOracle = True End If Catch ex As Exception GetMsgsFromOracle = False End Try End Function Private Function ProcessMessages() As Boolean Try ProcessMessages = False PrepareSQLInsert() PrepOraDel() i = 0 Dim Method As Integer Dim OraDataRow As DataRow c.ErrorLog(Now.ToString & "--Going to call message sending procedure", 2) For Each OraDataRow In OraDataTable.Rows With OraDataRow Method = GetMethod(.Item(0)) SQLInsCmd.Parameters("RelLifeTime").Value = c.RelLifetime SQLInsCmd.Parameters("Param1").Value = Nothing SQLInsCmd.Parameters("ID").Value = GenerateTransactionID() ' Nothing SQLInsCmd.Parameters("UID").Value = Nothing SQLInsCmd.Parameters("Param").Value = Nothing SQLInsCmd.Parameters("Credit").Value = 0 SQLInsCmd.ExecuteNonQuery() 'check the return value If SQLInsCmd.Parameters("ReturnValue").Value = 1 And SQLInsCmd.Parameters("OutPutParam").Value = 0 Then 'success 'delete the input record from the source table once it is logged c.ErrorLog(Now.ToString & "--Moved record successfully", 2) OraDataAdapter.DeleteCommand.Parameters("P(0)").Value = OraDataRow.Item(6) OraDataAdapter.DeleteCommand.ExecuteNonQuery() c.ErrorLog(Now.ToString & "--Deleted record successfully", 2) OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Committed record successfully", 2) i = i + 1 Else 'failure c.ErrorLog(Now.ToString & "--Failed to exec: " & c.DestIns & "Status: " & SQLInsCmd.Parameters("OutPutParam").Value & " and TrackId: " & SQLInsCmd.Parameters("TrackID").Value.ToString, 0) End If If File.Exists("stop.txt") Then c.ErrorLog(Now.ToString & "--Stop File Found", 1) 'ProcessMessages = True 'Exit Function Exit For End If End With Next OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Updated Oracle Table", 1) c.ErrorLog(Now.ToString & "--Moved " & i & " records from Oracle to SQL Table", 1) ProcessMessages = True Catch ex As Exception ProcessMessages = False c.ErrorLog(Now.ToString & "--MoveMsgsToSQL: " & ex.Message, 0) Finally OraDataTable.Clear() OraDataTable.Dispose() OraDataAdapter.Dispose() OraDelCmd.Dispose() OraDelCmd = Nothing OraSelCmd = Nothing OraDataTable = Nothing OraDataAdapter = Nothing End Try End Function Public Function GenerateTransactionID() As Int64 Dim SeqNo As Int64 Dim qry As String Dim SqlTransCmd As New OleDb.OleDbCommand qry = " select seqno from StoreSeqNo" SqlTransCmd.CommandType = CommandType.Text SqlTransCmd.Connection = SqlConn SqlTransCmd.CommandText = qry SeqNo = SqlTransCmd.ExecuteScalar If SeqNo > 2147483647 Then qry = "update StoreSeqNo set seqno=1" SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = 1 Else qry = "update StoreSeqNo set seqno=" & SeqNo + 1 SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = SeqNo End If End Function Private Function PrepareSQLInsert() As Boolean 'function to prepare the insert statement for the insert into the SQL stmt using 'the sql procedure SMSProcessAndDispatch Try Dim dr As DataRow SQLInsCmd = New OleDb.OleDbCommand With SQLInsCmd .CommandType = CommandType.StoredProcedure .Connection = SqlConn .CommandText = SQLInsProc .Parameters.Add("ReturnValue", OleDb.OleDbType.Integer) .Parameters("ReturnValue").Direction = ParameterDirection.ReturnValue .Parameters.Add("OutPutParam", OleDb.OleDbType.Integer) .Parameters("OutPutParam").Direction = ParameterDirection.Output .Parameters.Add("TrackID", OleDb.OleDbType.VarChar, 70) .Parameters.Add("RelLifeTime", OleDb.OleDbType.TinyInt) .Parameters("RelLifeTime").Direction = ParameterDirection.Input .Parameters.Add("Param1", OleDb.OleDbType.VarChar, 160) .Parameters("Param1").Direction = ParameterDirection.Input .Parameters.Add("TransID", OleDb.OleDbType.VarChar, 70) .Parameters("TransID").Direction = ParameterDirection.Input .Parameters.Add("UID", OleDb.OleDbType.VarChar, 20) .Parameters("UID").Direction = ParameterDirection.Input .Parameters.Add("Param", OleDb.OleDbType.VarChar, 160) .Parameters("Param").Direction = ParameterDirection.Input .Parameters.Add("CheckCredit", OleDb.OleDbType.Integer) .Parameters("CheckCredit").Direction = ParameterDirection.Input .Prepare() End With Catch ex As Exception c.ErrorLog(Now.ToString & "--PrepareSQLInsert: " & ex.Message) End Try End Function Private Function PrepOraDel() As Boolean OraDelCmd = New OleDb.OleDbCommand Try PrepOraDel = False With OraDelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = DelSrcSQL .Parameters.Add("P(0)", OleDb.OleDbType.VarChar, 160) 'RowID .Parameters("P(0)").Direction = ParameterDirection.Input .Prepare() End With OraDataAdapter.DeleteCommand = OraDelCmd PrepOraDel = True Catch ex As Exception PrepOraDel = False End Try End Function WHat i would like to know is, if there is anyway to speed up this program? Any ideas/suggestions would be highly appreciated... Regardss, Chetan

    Read the article

  • Type '_Default' already contains a definition

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2008 website. I have a Gridview. I included the Default.aspx and aspx.cs files below. But when I build this I get the below error: The Type '_Default' already contains a definition for 'btnOWrite' What do I need to do to fix this? I am not getting any errors now; just that this grid does not show up. Thanks! ASPX file: <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server"> <asp:Panel runat="server" ID="AuthenticatedMessagePanel"> <asp:Label runat="server" ID="WelcomeBackMessage"></asp:Label> <table> <tr> <td> <asp:Label ID="tableLabel" runat="server" Font-Bold="True" Text="Select target table:"></asp:Label> </td> <td> <asp:Label ID="inputLabel" runat="server" Font-Bold="True" Text="Select input file:"></asp:Label> </td> </tr> <tr> <td valign="top"> <asp:Label ID="feedbackLabel" runat="server"></asp:Label> <asp:SqlDataSource ID="SelectTables" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorks3_SelectTables %>" SelectCommand="getTableNames" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:QueryStringParameter DefaultValue="Person" Name="SchemaName" QueryStringField="SchemaName" Type="String" /> </SelectParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" DataSourceID="SelectTables" runat="server" Style="width: 400px;" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateSelectButton="True" DataKeyNames="TABLE_NAME"> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <Columns> <asp:BoundField HeaderText="TABLE_NAME" DataField="TABLE_NAME" /> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </td> <td valign="top"> <input id="uploadFile" type="file" size="26" runat="server" name="uploadFile" title="UploadFile" class="greybar" enableviewstate="True" /> </td> </tr> </table> <table> <tr> <td style="width:150px; height:50px"></td> <td valign="bottom" style="width:150px; height:50px"> <input id="btnOWrite" type="submit" value="Overwrite Data" runat="server" class="greybar" onserverclick="btnOWrite_Click" name="btnOWrite" />&nbsp; </td> <td style="width:100px"></td> <td valign="bottom" style="width:150px; height:50px"> <input id="btnAppend" type="submit" value="Append Data" runat="server" class="greybar" onserverclick="btnAppend_Click" name="btnAppend" /> </td> </tr> </table> </asp:Panel> <asp:Panel runat="Server" ID="AnonymousMessagePanel"> <asp:HyperLink runat="server" ID="lnkLogin" Text="Log In" NavigateUrl="~/Login.aspx"> </asp:HyperLink> </asp:Panel> </asp:Content> ASPX.CS file: using System; using System.Collections; 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.Collections.Generic; using System.IO; using System.Drawing; using System.ComponentModel; using System.Data.SqlClient; using ADONET_namespace; using System.Security.Principal; //using System.Windows; public partial class _Default : System.Web.UI.Page //namespace AddFileToSQL { //protected System.Web.UI.HtmlControls.HtmlInputFile uploadFile; protected System.Web.UI.HtmlControls.HtmlInputButton btnOWrite; protected System.Web.UI.HtmlControls.HtmlInputButton btnAppend; protected System.Web.UI.WebControls.Label Label1; protected static string inputfile = ""; public static string targettable; public static string selection; // Number of controls added to view state protected int default_NumberOfControls { get { if (ViewState["default_NumberOfControls"] != null) { return (int)ViewState["default_NumberOfControls"]; } else { return 0; } } set { ViewState["default_NumberOfControls"] = value; } } protected void uploadFile_onclick(object sender, EventArgs e) { } protected void Load_GridData() { //GridView1.DataSource = ADONET_methods.DisplaySchemaTables(); //GridView1.DataBind(); } protected void btnOWrite_Click(object sender, EventArgs e) { if (uploadFile.PostedFile.ContentLength > 0) { feedbackLabel.Text = "You do not have sufficient access to overwrite table records."; } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void btnAppend_Click(object sender, EventArgs e) { string fullpath = Page.Request.PhysicalApplicationPath; string path = uploadFile.PostedFile.FileName; if (File.Exists(path)) { // Create a file to write to. try { StreamReader sr = new StreamReader(path); string s = ""; while (sr.Peek() > 0) s = sr.ReadLine(); sr.Close(); } catch (IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } } if (uploadFile.PostedFile.ContentLength > 0) { inputfile = System.IO.File.ReadAllText(path); Session["Message"] = inputfile; Response.Redirect("DataMatch.aspx"); } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WelcomeBackMessage.Text = "Welcome back, " + User.Identity.Name + "!"; // Reference the CustomPrincipal / CustomIdentity CustomIdentity ident = User.Identity as CustomIdentity; if (ident != null) WelcomeBackMessage.Text += string.Format(" You are the {0} of {1}.", ident.Title, ident.CompanyName); AuthenticatedMessagePanel.Visible = true; AnonymousMessagePanel.Visible = false; if (!Page.IsPostBack) { Load_GridData(); } } else { AuthenticatedMessagePanel.Visible = false; AnonymousMessagePanel.Visible = true; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; targettable = row.Cells[2].Text; } }

    Read the article

  • Profile System: User share the same id

    - by Malcolm Frexner
    I have a strange effect on my site when it is under heavy load. I randomly get the properties of other users settings. I have my own implementation of the profile system so I guess I can not blame the profile system itself. I just need a point to start debugging from. I guess there is a cookie-value that maps to an Profile entry somewhere. Is there any chance to see how this mapping works? Here is my profile provider: using System; using System.Text; using System.Configuration; using System.Web; using System.Web.Profile; using System.Collections; using System.Collections.Specialized; using B2CShop.Model; using log4net; using System.Collections.Generic; using System.Diagnostics; using B2CShop.DAL; using B2CShop.Model.RepositoryInterfaces; [assembly: log4net.Config.XmlConfigurator()] namespace B2CShop.Profile { public class B2CShopProfileProvider : ProfileProvider { private static readonly ILog _log = LogManager.GetLogger(typeof(B2CShopProfileProvider)); // Get an instance of the Profile DAL using the ProfileDALFactory private static readonly B2CShop.DAL.UserRepository dal = new B2CShop.DAL.UserRepository(); // Private members private const string ERR_INVALID_PARAMETER = "Invalid Profile parameter:"; private const string PROFILE_USER = "User"; private static string applicationName = B2CShop.Model.Configuration.ApplicationConfiguration.MembershipApplicationName; /// <summary> /// The name of the application using the custom profile provider. /// </summary> public override string ApplicationName { get { return applicationName; } set { applicationName = value; } } /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "B2C Shop Custom Provider"); } if (string.IsNullOrEmpty(name)) name = "b2c_shop"; if (config["applicationName"] != null && !string.IsNullOrEmpty(config["applicationName"].Trim())) applicationName = config["applicationName"]; base.Initialize(name, config); } /// <summary> /// Returns the collection of settings property values for the specified application instance and settings property group. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application use.</param> /// <param name="collection">A System.Configuration.SettingsPropertyCollection containing the settings property group whose values are to be retrieved.</param> /// <returns>A System.Configuration.SettingsPropertyValueCollection containing the values for the specified settings property group.</returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { string username = (string)context["UserName"]; bool isAuthenticated = (bool)context["IsAuthenticated"]; //if (!isAuthenticated) return null; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection(); foreach (SettingsProperty prop in collection) { SettingsPropertyValue pv = new SettingsPropertyValue(prop); switch (pv.Property.Name) { case PROFILE_USER: if (!String.IsNullOrEmpty(username)) { pv.PropertyValue = GetUser(uniqueID); } break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } svc.Add(pv); } return svc; } /// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application usage.</param> /// <param name="collection">A System.Configuration.SettingsPropertyValueCollection representing the group of property settings to set.</param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string username = (string)context["UserName"]; CheckUserName(username); bool isAuthenticated = (bool)context["IsAuthenticated"]; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); if (uniqueID == 0) { uniqueID = dal.CreateProfileForUser(username, isAuthenticated, ApplicationName); } foreach (SettingsPropertyValue pv in collection) { if (pv.PropertyValue != null) { switch (pv.Property.Name) { case PROFILE_USER: SetUser(uniqueID, (UserInfo)pv.PropertyValue); break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } } } UpdateActivityDates(username, false); } // Profile gettters // Retrieve UserInfo private static UserInfo GetUser(int userID) { return dal.GetUser(userID); } // Update account info private static void SetUser(int uniqueID, UserInfo user) { user.UserID = uniqueID; dal.SetUser(user); } // UpdateActivityDates // Updates the LastActivityDate and LastUpdatedDate values // when profile properties are accessed by the // GetPropertyValues and SetPropertyValues methods. // Passing true as the activityOnly parameter will update // only the LastActivityDate. private static void UpdateActivityDates(string username, bool activityOnly) { dal.UpdateActivityDates(username, activityOnly, applicationName); } /// <summary> /// Deletes profile properties and information for the supplied list of profiles. /// </summary> /// <param name="profiles">A System.Web.Profile.ProfileInfoCollection of information about profiles that are to be deleted.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteProfiles(ProfileInfoCollection profiles) { int deleteCount = 0; foreach (ProfileInfo p in profiles) if (DeleteProfile(p.UserName)) deleteCount++; return deleteCount; } /// <summary> /// Deletes profile properties and information for profiles that match the supplied list of user names. /// </summary> /// <param name="usernames">A string array of user names for profiles to be deleted.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteProfiles(string[] usernames) { int deleteCount = 0; foreach (string user in usernames) if (DeleteProfile(user)) deleteCount++; return deleteCount; } // DeleteProfile // Deletes profile data from the database for the specified user name. private static bool DeleteProfile(string username) { CheckUserName(username); return dal.DeleteAnonymousProfile(username, applicationName); } // Verifies user name for sise and comma private static void CheckUserName(string userName) { if (string.IsNullOrEmpty(userName) || userName.Length > 256 || userName.IndexOf(",") > 0) throw new ApplicationException(ERR_INVALID_PARAMETER + " user name."); } /// <summary> /// Deletes all user-profile data for profiles in which the last activity date occurred before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are deleted.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { string[] userArray = new string[0]; dal.GetInactiveProfiles((int)authenticationOption, userInactiveSinceDate, ApplicationName).CopyTo(userArray, 0); return DeleteProfiles(userArray); } /// <summary> /// Retrieves profile information for profiles in which the user name matches the specified user names. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information // for profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves profile information for profiles in which the last activity date occurred on or before the specified date and the user name matches the specified user name. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user profile information for inactive profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves user profile data for all profiles in the data source. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information for all profiles in the data source.</returns> public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves user-profile data from the data source for profiles in which the last activity date occurred on or before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information about the inactive profiles.</returns> public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// Returns the number of profiles in which the last activity date occurred on or before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <returns>The number of profiles in which the last activity date occurred on or before the specified date.</returns> public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { int inactiveProfiles = 0; ProfileInfoCollection profiles = GetProfileInfo(authenticationOption, null, userInactiveSinceDate, 0, 0, out inactiveProfiles); return inactiveProfiles; } //Verifies input parameters for page size and page index. private static void CheckParameters(int pageIndex, int pageSize) { if (pageIndex < 1 || pageSize < 1) throw new ApplicationException(ERR_INVALID_PARAMETER + " page index."); } //GetProfileInfo //Retrieves a count of profiles and creates a //ProfileInfoCollection from the profile data in the //database. Called by GetAllProfiles, GetAllInactiveProfiles, //FindProfilesByUserName, FindInactiveProfilesByUserName, //and GetNumberOfInactiveProfiles. //Specifying a pageIndex of 0 retrieves a count of the results only. private static ProfileInfoCollection GetProfileInfo(ProfileAuthenticationOption authenticationOption, string usernameToMatch, object userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { ProfileInfoCollection profiles = new ProfileInfoCollection(); totalRecords = 0; // Count profiles only. if (pageSize == 0) return profiles; int counter = 0; int startIndex = pageSize * (pageIndex - 1); int endIndex = startIndex + pageSize - 1; DateTime dt = new DateTime(1900, 1, 1); if (userInactiveSinceDate != null) dt = (DateTime)userInactiveSinceDate; /* foreach(CustomProfileInfo profile in dal.GetProfileInfo((int)authenticationOption, usernameToMatch, dt, applicationName, out totalRecords)) { if(counter >= startIndex) { ProfileInfo p = new ProfileInfo(profile.UserName, profile.IsAnonymous, profile.LastActivityDate, profile.LastUpdatedDate, 0); profiles.Add(p); } if(counter >= endIndex) { break; } counter++; } */ return profiles; } } } This is how I use it in the controller: public ActionResult AddTyreToCart(CartViewModel model) { string profile = Request.IsAuthenticated ? Request.AnonymousID : User.Identity.Name; } I would like to debug: How can 2 users who provide different cookies get the same profileid? EDIT Here is the code for getuniqueid public int GetUniqueID(string userName, bool isAuthenticated, bool ignoreAuthenticationType, string appName) { SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = userName; parms[1].Value = appName; if (!ignoreAuthenticationType) { Array.Resize(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit) { Value = !isAuthenticated }; } int userID; object retVal = null; retVal = SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["SQLOrderB2CConnString"].ConnectionString, CommandType.StoredProcedure, "getProfileUniqueID", parms); if (retVal == null) userID = CreateProfileForUser(userName, isAuthenticated, appName); else userID = Convert.ToInt32(retVal); return userID; } And this is the SP: CREATE PROCEDURE [dbo].[getProfileUniqueID] @Username VarChar( 256), @ApplicationName VarChar( 256), @IsAnonymous bit = null AS BEGIN SET NOCOUNT ON; /* [getProfileUniqueID] created 08.07.2009 mf Retrive unique id for current user */ SELECT UniqueID FROM dbo.Profiles WHERE Username = @Username AND ApplicationName = @ApplicationName AND IsAnonymous = @IsAnonymous or @IsAnonymous = null END

    Read the article

< Previous Page | 4 5 6 7 8