Search Results

Search found 204 results on 9 pages for 'sqldatareader'.

Page 8/9 | < Previous Page | 4 5 6 7 8 9  | Next Page >

  • How to eliminate one of my extra DropDownLists in C#?

    - by salvationishere
    I'm developing a C#/SQL web app in VS 2008 but for some reason I have one extra DropDownList. The very first dropdownlist displaying is empty. Can you help me identify the cause of this behavior? I'm baffled! An excerpt of my code is below. private DropDownList[] newcol; // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks //ddlList.Style["position"] = "absolute"; //ddl.Style["top"] = 80 + "px"; //ddl.Style["left"] = 0 + "px"; dr2.Close(); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } }

    Read the article

  • How to call base abstract or interface from DAL into BLL?

    - by programmerist
    How can i access abstract class in BLL ? i shouldn't see GenAccessor in BLL it must be private class GenAccessor . i should access Save method over _AccessorForSQL. ok? MY BLL cs: public class AccessorForSQL: GenoTip.DAL._AccessorForSQL { public bool Save(string Name, string SurName, string Adress) { ListDictionary ld = new ListDictionary(); ld.Add("@Name", Name); ld.Add("@SurName", SurName); ld.Add("@Adress", Adress); return **base.Save("sp_InsertCustomers", ld, CommandType.StoredProcedure);** } } i can not access base.Save....???????? it is my DAL Layer: namespace GenoTip.DAL { public abstract class _AccessorForSQL { public abstract bool Save(string sp, ListDictionary ld, CommandType cmdType); public abstract bool Update(); public abstract bool Delete(); public abstract DataSet Select(); } private class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • sharepoint custom aspx page with database connection

    - by Megini
    hi there i have created a custom aspx page whithin my sharepoint site with a sql server connection to a database on that server to select data when i view the page it works but when another user tries to view it it gives the following error : Server Error in '/' Application. Login failed for user 'GRINCOR\GuguK'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'GRINCOR\GuguK'. Source Error: The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL: Add a "Debug=true" directive at the top of the file that generated the error. Example: <%@ Page Language="C#" Debug="true" % or: 2) Add the following section to the configuration file of your application: Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode. Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario. Stack Trace: [SqlException (0x80131904): Login failed for user 'GRINCOR\GuguK'.] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +248 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +245 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2811 System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +327 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +2445370 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +2445224 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +354 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +703 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +54 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +2414776 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +92 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +1657 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +84 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +1645767 System.Data.SqlClient.SqlConnection.Open() +258 ASP.d7922f0d_ac20_4f87_91a2_a99a52c2b2fa__233736835.DisplayData() in C:\inetpub\wwwroot\wss\VirtualDirectories\80\sites\hrportal2\tester.aspx:151 ASP.d7922f0d_ac20_4f87_91a2_a99a52c2b2fa_233736835._RenderMain(HtmlTextWriter __w, Control parameterContainer) in C:\inetpub\wwwroot\wss\VirtualDirectories\80\sites\hrportal2\tester.aspx:346 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +115 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +240 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +42 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +240 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +253 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +87 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +53 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +240 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +42 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +240 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +240 System.Web.UI.Page.Render(HtmlTextWriter writer) +38 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4240 Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3601 can someone give me a solution to this problem ? i am using sharepoint services 3.0

    Read the article

  • List<> of objects, different types, sort and pull out types individually?

    - by Brazos
    I've got a handful of products, any, all, or none of which may be associated with a specific submission. All 7 products are subclasses of the class Product. I need to store all the products associated with a submission, and then retrieve them and their field data on my presentation layer. I've been using a List, and List, but when I use the OfType, I throw an error saying that I can't implicitly convert systems.generic.IEnumerable to type 'Product'. I've tried to cast, but to no avail. When I use prodlist.OfType<EPL>(); there are no errors, but when I try and store that in an instance of EPL "tempEpl", I get the aforementioned cast-related error. What gives? Code below. ProductService pserv = new ProductService(); IList<object> prodlist = pserv.getProductById(x); EPL tempEpl = new EPL(); if ((prodlist.OfType<EPL>()) != null) { tempEpl = prodlist.OfType<EPL>(); // this throws a conversion error. } the Data layer List<object> TempProdList = new List<object>(); conn.Open(); SqlCommand EplCmd = new SqlCommand(EPLQuery, conn); SqlDataReader EplRead = null; EplRead = EplCmd.ExecuteReader(); EPL TempEpl = new EPL(); if (EplRead.Read()) { TempEpl.Entity1 = EplRead.GetString(0); TempEpl.Employees1 = EplRead.GetInt32(1); TempEpl.CA1 = EplRead.GetInt32(2); TempEpl.MI1 = EplRead.GetInt32(3); TempEpl.NY1 = EplRead.GetInt32(4); TempEpl.NJ1 = EplRead.GetInt32(5); TempEpl.PrimEx1 = EplRead.GetInt32(6); TempEpl.EplLim1 = EplRead.GetInt32(7); TempEpl.EplSir1 = EplRead.GetInt32(8); TempEpl.Premium1 = EplRead.GetInt32(9); TempEpl.Wage1 = EplRead.GetInt32(10); TempEpl.Sublim1 = EplRead.GetInt32(11); TempProdList.Add(TempEpl); }

    Read the article

  • How do I write sql data into a textbox after a submit type event

    - by Matt
    Finishing up some homework and Im having trouble with figuring out how to take information generated in sql column(a primary key set up to assign a record number to a customer example 1046) at submit and writing it to my redirected recipt page. I call it recipt.aspx. Any takers Professor says to use a datareader...but things go bad after that. public partial class _Default : System.Web.UI.Page { String cnStr = "EDITED FOR THE PURPOSE OF NOT DISPLAYED SQL SERVERta Source=111.11.111.11; uid=xxxxxxx; password=xxxx; database=xxxxxx; "; String insertStr; SqlDataReader reader; SqlConnection myConnection = new SqlConnection(); protected void submitbutton_Click(object sender, EventArgs e) { myConnection.ConnectionString = cnStr; try { //more magic happens as myConnection opens myConnection.Open(); insertStr = "insert into connectAssignment values ('" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + bigtextthing.Text + "','" + DropDownList1.SelectedItem.Value + "')"; //magic happens as Connection string is assigned to connection object and passes in the SQL statment //associate the command to the the myConnection connection object SqlCommand cmd = new SqlCommand(insertStr, myConnection); cmd.ExecuteNonQuery(); Session["passmyvalue1"] = TextBox2.Text; Session["passmyvalue2"] = TextBox3.Text; Session["passmyvalue3"] = TextBox4.Text; Session["passmyvalue4"] = TextBox5.Text; Session["passmyvalue5"] = bigtextthing.Text; Session["I NEED SOME HELP RIGHT HERE"] =Textbox6.Text; Response.Redirect("receipt.aspx"); } catch { bigtextthing.Text = "Error submitting" + "Possible casues: Internet is down,server is down, check your settings!"; } finally { myConnection.Close(); TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; TextBox5.Text = ""; bigtextthing.Text = ""; } //reset validators? } The recipt page public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(Session["passmyvalue1"] != null) { TextBox1.Text = (string)Session["passmyvalue1"]; TextBox2.Text = (string)Session["passmyvalue2"]; TextBox3.Text = (string)Session["passmyvalue3"]; TextBox4.Text = (string)Session["passmyvalue4"]; TextBox5.Text = (string)Session["passmyvalue5"]; TextBox6.Text = I don't know ; } } } THanks for the help

    Read the article

  • building list of child objects inside main object

    - by Asdfg
    I have two tables like this: Category: Id Name ------------------ 1 Cat1 2 Cat2 Feature: Id Name CategoryId -------------------------------- 1 F1 1 2 F2 1 3 F3 2 4 F4 2 5 F5 2 In my .Net classes, i have two POCO classes like this: public class Category { public int Id {get;set;} public int Name {get;set;} public IList<Feature> Features {get;set;} } public class Feature { public int Id {get;set;} public int CategoryId {get;set;} public int Name {get;set;} } I am using a stored proc that returns me a result set by joining these 2 tables. This is how my Stored Proc returns the result set. SELECT c.CategoryId, c.Name Category, f.FeatureId, f.Name Feature FROM Category c INNER JOIN Feature f ON c.CategoryId = f.CategoryId ORDER BY c.Name --Resultset produced by the above query CategoryId CategoryName FeatureId FeatureName --------------------------------------------------- 1 Cat1 1 F1 1 Cat1 2 F2 2 Cat2 3 F3 2 Cat2 4 F4 2 Cat2 5 F5 Now if i want to build the list of categories in my .Net code, i have to loop thru the result set and add features unless the category changes. This is how my .Net code looks like that builds Categories and Features. List<Category> categories = new List<Category>(); Int32 lastCategoryId = 0; Category c = new Category(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { //Check if the categoryid is same as previous one. //If Not, add new category. //If Yes, dont add the category. if (lastCategoryId != Convert.ToInt32(reader["CategoryId"])) { c = new Category { Id = Convert.ToInt32(reader["CategoryId"]), Name = reader["CategoryName"].ToString() }; c.Features = new List<Feature>(); categories.Add(c); } lastCategoryId = Convert.ToInt32(reader["CategoryId"]); //Add Feature c.Features.Add(new Feature { Name = reader["FeatureName"].ToString(), Id = Convert.ToInt32(reader["FeatureId"]) }); } return categories; } I was wondering if there is a better way to do build the list of Categories?

    Read the article

  • Speed up a web service for auto complete and avoid too many method calls.

    - by jphenow
    So I've got my jquery autocomplete 'working,' but its a little fidgety since I call the webservice method each time a keydown() fires so I get lots of methods hanging and sometimes to get the "auto" to work I have to type it out and backspace a bit because i'm assuming it got its return value a little slow. I've limited the query results to 8 to mininmize time. Is there anything i can do to make this a little snappier? This thing seems near useless if I don't get it a little more responsive. javascript $("#clientAutoNames").keydown(function () { $.ajax({ type: "POST", url: "WebService.asmx/LoadData", data: "{'input':" + JSON.stringify($("#clientAutoNames").val()) + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data.d != null) { var serviceScript = data.d; } $("#autoNames").html(serviceScript); $('#clientAutoNames').autocomplete({ minLength: 2, source: autoNames, delay: 100, focus: function (event, ui) { $('#project').val(ui.item.label); return false; }, select: function (event, ui) { $('#clientAutoNames').val(ui.item.label); $('#projectid').val(ui.item.value); $('#project-description').html(ui.item.desc); pkey = $('#project-id').val; return false; } }) .data("autocomplete")._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.label + "<br>" + item.desc + "</a>") .appendTo(ul); } } }); }); WebService.asmx <WebMethod()> _ Public Function LoadData(ByVal input As String) As String Dim result As String = "<script>var autoNames = [" Dim sqlOut As Data.SqlClient.SqlDataReader Dim connstring As String = *Datasource* Dim strSql As String = "SELECT TOP 2 * FROM v_Clients WHERE (SearchName Like '" + input + "%') ORDER BY SearchName" Dim cnn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(connstring) Dim cmd As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand(strSql, cnn) cnn.Open() sqlOut = cmd.ExecuteReader() Dim c As Integer = 0 While sqlOut.Read() result = result + "{" result = result + "value: '" + sqlOut("ContactID").ToString() + "'," result = result + "label: '" + sqlOut("SearchName").ToString() + "'," 'result = result + "desc: '" + title + " from " + company + "'," result = result + "}," End While result = result + "];</script>" sqlOut.Close() cnn.Close() Return result End Function I'm sure I'm just going about this slightly wrong or not doing a better balance of calls or something. Greatly appreciated!

    Read the article

  • How to eliminate one of my extra DropDownLists in ASP.NET?

    - by salvationishere
    I'm developing a C#/SQL web app in VS 2008 but for some reason I have one extra DropDownList. The very first dropdownlist displaying is empty. Can you help me identify the cause of this behavior? I'm baffled! An excerpt of my code is below. private DropDownList[] newcol; // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks //ddlList.Style["position"] = "absolute"; //ddl.Style["top"] = 80 + "px"; //ddl.Style["left"] = 0 + "px"; dr2.Close(); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } }

    Read the article

  • Get return values from a stored procedure in c# (login process)

    - by Jin
    Hi all, I am trying to use a Stored Procedure which takes two parameters (login, pw) and returns the user info. If I execute the SP manually, I get Session_UID User_Group_Name Sys_User_Name ------------------------------------ -------------------------------------------------- - NULL Administrators NTMSAdmin No rows affected. (1 row(s) returned) @RETURN_VALUE = 0 Finished running [dbo].[p_SYS_Login]. But with the code below, I only get the return value. do you know how to get the other values shown above like Session_UID, User_Group_Name, and Sys_User_Name ? if you see the commented part below code. I tried to add some output parameters but it doesn't work with incorrect number of parameters error. string strConnection = Settings.Default.ConnectionString; using (SqlConnection conn = new SqlConnection(strConnection)) { using (SqlCommand cmd = new SqlCommand()) { SqlDataReader rdr = null; cmd.Connection = conn; cmd.CommandText = "p_SYS_Login"; //cmd.CommandText = "p_sys_Select_User_Group"; cmd.CommandType = CommandType.StoredProcedure; SqlParameter paramReturnValue = new SqlParameter(); paramReturnValue.ParameterName = "@RETURN_VALUE"; paramReturnValue.SqlDbType = SqlDbType.Int; paramReturnValue.SourceColumn = null; paramReturnValue.Direction = ParameterDirection.ReturnValue; //SqlParameter paramGroupName = new SqlParameter("@User_Group_Name", SqlDbType.VarChar, 50); //paramGroupName.Direction = ParameterDirection.Output; //SqlParameter paramUserName = new SqlParameter("@Sys_User_Name", SqlDbType.VarChar, 50); //paramUserName.Direction = ParameterDirection.Output; cmd.Parameters.Add(paramReturnValue); //cmd.Parameters.Add(paramGroupName); //cmd.Parameters.Add(paramUserName); cmd.Parameters.AddWithValue("@Sys_Login", textUserID.Text); cmd.Parameters.AddWithValue("@Sys_Password", textPassword.Text); try { conn.Open(); object result = cmd.ExecuteNonQuery(); int returnValue = (int)cmd.Parameters["@RETURN_VALUE"].Value; if (returnValue == 0) { Hide(); Program.MapForm.Show(); } else if (returnValue == 1) { MessageBox.Show("The username or password you entered is incorrect", "NTMS Login", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (returnValue == 2) { MessageBox.Show("This account is disabled", "NTMS Login", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { MessageBox.Show("Database error. Please contact administrator", "NTMS Login", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { string message = ex.Message; string caption = "MAVIS Exception"; MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBox.Show( message, caption, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } } } Thanks for your help.

    Read the article

  • SMO ConnectionContext.StatementTimeout setting is ignored

    - by Woody
    I am successfully using Powershell with SMO to backup most databases. However, I have several large databases in which I receive a "timeout" error "System.Data.SqlClient.SqlException: Timeout expired". The timout consistently occurs at 10 minutes. I have tried setting ConnectionContext.StatementTimeout to 0, 6000, and to [System.Int32]::MaxValue. The setting made no difference. I have found a number of Google references which indicate setting it to 0 makes it unlimited. No matter what I try, the timeouts consistently occur at 10 minutes. I even set Remote Query Timeout on the server to 0 (via Studio Manager) to no avail. Below is my SMO connection where I set the time out and the actual backup function. Further below is the output from my script. UPDATE Interestingly enough, I wrote the backup function in C# using VS 2008 and the timeout override does work within that environment. I am in the process of incorporating that C# process into my Powershell Script until I can find out why the timeout override does not work with just Powershell. This is extremely annoying! function New-SMOconnection { Param ($server, $ApplicationName= "PowerShell SMO", [int]$StatementTimeout = 0 ) # Write-Debug "Function: New-SMOconnection $server $connectionname $commandtimeout" if (test-path variable:\conn) { $conn.connectioncontext.disconnect() } else { $conn = New-Object('Microsoft.SqlServer.Management.Smo.Server') $server } $conn.connectioncontext.applicationName = $applicationName $conn.ConnectionContext.StatementTimeout = $StatementTimeout $conn.connectioncontext.Connect() $conn } $smo = New-SMOConnection -server $server if ($smo.connectioncontext.isopen -eq $false) { Throw "Could not connect to server $($server)." } Function Backup-Database { Param([string]$dbname) $db = $smo.Databases.get_Item($dbname) if (!$db) {"Database $dbname was not found"; Return} $sqldir = $smo.Settings.BackupDirectory + "\$($smo.name -replace ("\\", "$"))" $s = ($server.Split('\'))[0] $basedir = "\\$s\" + $($sqldir -replace (":", "$")) $dt = get-date -format yyyyMMdd-HHmmss $dbbk = new-object ('Microsoft.SqlServer.Management.Smo.Backup') $dbbk.Action = 'Database' $dbbk.BackupSetDescription = "Full backup of " + $dbname $dbbk.BackupSetName = $dbname + " Backup" $dbbk.Database = $dbname $dbbk.MediaDescription = "Disk" $target = "$basedir\$dbname\FULL" if (-not(Test-Path $target)) { New-Item $target -ItemType directory | Out-Null} $device = "$sqldir\$dbname\FULL\" + $($server -replace("\\", "$")) + "_" + $dbname + "_FULL_" + $dt + ".bak" $dbbk.Devices.AddDevice($device, 'File') $dbbk.Initialize = $True $dbbk.Incremental = $false $dbbk.LogTruncation = [Microsoft.SqlServer.Management.Smo.BackupTruncateLogType]::Truncate If (!$copyonly) { If ($kill) {$smo.KillAllProcesses($dbname)} $dbbk.SqlBackupAsync($server) } $dbbk } Started SQL backups for server LCFSQLxxx\SQLxxx at 05/06/2010 15:33:16 Statement TimeOut value set to 0. DatabaseName : OperationsManagerDW StartBackupTime : 5/6/2010 3:33:16 PM EndBackupTime : 5/6/2010 3:43:17 PM StartCopyTime : 1/1/0001 12:00:00 AM EndCopyTime : 1/1/0001 12:00:00 AM CopiedFiles : Status : Failed ErrorMessage : System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The backup or restore was aborted. 10 percent processed. 20 percent processed. 30 percent processed. 40 percent processed. 50 percent processed. 60 percent processed. 70 percent processed. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType) Ended backups at 05/06/2010 15:43:23

    Read the article

  • Parsing a JSON Response from a .Net webservice

    - by Maskau
    Just to get this out in the open I am new to JAVA, KSOAP, and JSON. So I'll try to explain this the best I can. A while ago I created a webservice to be consumed by Blackberry Apps that we're built using the plug in for Visual Studio. Now the project I am working on, I want to consume the same webservice for Android devices. For the most part I have the base code for the Android app done and working. Here's my problem: I can successfully call the webservice and get a response. I know from creating the webservice that it sends a JSON response. My problem is trying to parse through the JSON response. I have found a few examples that I have been suiting to my needs however I am hung up on one thing. In the JSON each element is preceeded by "anyType" which is forcing my code to return no results (Ultimately I am binding the data to an ArrayList) Here's what I get if I "getProperty(0).toString()... anyType{Artist=anyType{TrackName=Champagne Supernova;}; Here is the code I am using to parse the JSON Object.... SoapObject gr = (SoapObject)envelope.getResponse(); String ro = gr.getProperty(0).toString(); //Added just to see structure of response Artist_Result.add(gr.toString()); if (ro.startsWith("{")) { JSONObject JSONObj = new JSONObject(ro); Iterator<String> itr = JSONObj.keys(); while (itr.hasNext()) { String key = (String)itr.next(); String value = JSONObj.getString(key); //bundleResult.putString(key, value); Artist_Result.add(value); } } else if (ro.startsWith("[")) { JSONArr = new JSONArray(ro); for (int i = 0; i < JSONArr.length(); i++) { JSONObj = (JSONObject)JSONArr.get(i); //bundleResult.putString(String.valueOf(i), JSONObj.toString()); Artist_Result.add(JSONObj.toString()); } } WebService Code: [WebMethod] [return: System.Xml.Serialization.XmlArrayItemAttribute(typeof(Artist))] public Artist[] GetArtist(string ArtistQuery) { // All the SQL Stuff Here SqlDataReader sReader; sReader = cmd.ExecuteReader(); List<Artist> Artists = new List<Artist>(); while (sReader.Read()) { Artist result = new Artist(); result.TrackName = sReader.GetString(0); Artists.Add(result); } sReader.Close(); sqlConn.Close(); return Artists.ToArray(); } public class Artist { public string TrackName; } Sample of XML Output from a browser: <?xml version="1.0" encoding="utf-8" ?> - <ArrayOfArtist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://bb.mcrcog.com/"> - <Artist> <TrackName>Champagne Supernova</TrackName> </Artist> - <Artist> <TrackName>Don't Look Back In Anger</TrackName> </Artist> - <Artist> <TrackName>D'you Know What I Mean</TrackName> </Artist> - <Artist> <TrackName>Go Let It Out</TrackName> </Artist> I have a feeling I will need to implement a Class, and Getters/Setters on the Android side. I'm just not sure how to go about doing that. Any help would be greatly appreciated!

    Read the article

  • If record exists in database, UPDATE a single column

    - by Doug
    I have a bulk uploading object in place that is being used to bulk upload roughly 25-40 image files at a time. Each image is about 100-150 kb in size. During the upload, I've created a for each loop that takes the file name of the image (minus the file extension) to write it into a column named "sku". Also, for each file being uploaded, the date is recorded to a column named DateUpdated, as well as some image path data. Here is my c# code: protected void graphicMultiFileButton_Click(object sender, EventArgs e) { //graphicMultiFile is the ID of the bulk uploading object ( provided by Dean Brettle: http://www.brettle.com/neatupload ) if (graphicMultiFile.Files.Length > 0) { foreach (UploadedFile file in graphicMultiFile.Files) { //strip ".jpg" from file name (will be assigned as SKU) string sku = file.FileName.Substring(0, file.FileName.Length - 4); //assign the directory where the images will be stored on the server string directoryPath = Server.MapPath("~/images/graphicsLib/" + file.FileName); //ensure that if image existes on server that it will get overwritten next time it's uploaded: file.MoveTo(directoryPath, MoveToOptions.Overwrite); //current sql that inserts a record to the db SqlCommand comm; SqlConnection conn; string connectionString = ConfigurationManager.ConnectionStrings["DataConnect"].ConnectionString; conn = new SqlConnection(connectionString); comm = new SqlCommand("INSERT INTO GraphicsLibrary (sku, imagePath, DateUpdated) VALUES (@sku, @imagePath, @DateUpdated)", conn); comm.Parameters.Add("@sku", System.Data.SqlDbType.VarChar, 50); comm.Parameters["@sku"].Value = sku; comm.Parameters.Add("@imagePath", System.Data.SqlDbType.VarChar, 300); comm.Parameters["@imagePath"].Value = "images/graphicsLib/" + file.FileName; comm.Parameters.Add("@DateUpdated", System.Data.SqlDbType.DateTime); comm.Parameters["@DateUpdated"].Value = DateTime.Now; conn.Open(); comm.ExecuteNonQuery(); conn.Close(); } } } After images are uploaded, managers will go back and re-upload images that have previously been uploaded. This is because these product images are always being revised and improved. For each new/improved image, the file name and extension will remain the same - so that when image 321-54321.jpg was first uploaded to the server, the new/improved version of that image will still have the image file name as 321-54321.jpg. I can't say for sure if the file sizes will remain in the 100-150KB range. I'll assume that the image file size will grow eventually. When images get uploaded (again), there of course will be an existing record in the database for that image. What is the best way to: Check the database for the existing record (stored procedure or SqlDataReader or create a DataSet ...?) Then if record exists, simply UPDATE that record so that the DateUpdated column gets today's date. If no record exists, do the INSERT of the record as normal. Things to consider: If the record exists, we'll let the actual image be uploaded. It will simply overwrite the existing image so that the new version gets displayed on the web. We're using SQL Server 2000 on hosted environment (DiscountAsp). I'm programming in C#. The uploading process will be used by about 2 managers a few times a month (each) - which to me is not a allot of usage. Although I'm a jr. developer, I'm guessing that a stored procedure would be the way to go. Just seems more efficient - to do this record check away from the for each loop... but not sure. I'd need extra help writing a sproc, since I don't have too much experience with them. Thank everyone...

    Read the article

  • Download binary file From SQL Server 2000

    - by kareemsaad
    I inserted binary files (images, PDF, videos..) and I want to retrieve this file to download it. I used generic handler page as this public void ProcessRequest (HttpContext context) { using (System.Data.SqlClient.SqlConnection con = Connection.GetConnection()) { String Sql = "Select BinaryData From ProductsDownload Where Product_Id = @Product_Id"; SqlCommand com = new SqlCommand(Sql, con); com.CommandType = System.Data.CommandType.Text; com.Parameters.Add(Parameter.NewInt("@Product_Id", context.Request.QueryString["Product_Id"].ToString())); SqlDataReader dr = com.ExecuteReader(); if (dr.Read() && dr != null) { Byte[] bytes; bytes = Encoding.UTF8.GetBytes(String.Empty); bytes = (Byte[])dr["BinaryData"]; context.Response.BinaryWrite(bytes); dr.Close(); } } } and this is my table CREATE TABLE [ProductsDownload] ( [ID] [bigint] IDENTITY (1, 1) NOT NULL , [Product_Id] [int] NULL , [Type_Id] [int] NULL , [Name] [nvarchar] (200) COLLATE Arabic_CI_AS NULL , [MIME] [varchar] (50) COLLATE Arabic_CI_AS NULL , [BinaryData] [varbinary] (4000) NULL , [Description] [nvarchar] (500) COLLATE Arabic_CI_AS NULL , [Add_Date] [datetime] NULL , CONSTRAINT [PK_ProductsDownload] PRIMARY KEY CLUSTERED ( [ID] ) ON [PRIMARY] , CONSTRAINT [FK_ProductsDownload_DownloadTypes] FOREIGN KEY ( [Type_Id] ) REFERENCES [DownloadTypes] ( [ID] ) ON DELETE CASCADE ON UPDATE CASCADE , CONSTRAINT [FK_ProductsDownload_Product] FOREIGN KEY ( [Product_Id] ) REFERENCES [Product] ( [Product_Id] ) ON DELETE CASCADE ON UPDATE CASCADE ) ON [PRIMARY] GO And use data list has label for file name and button to download file as <asp:DataList ID="DataList5" runat="server" DataSource='<%#GetData(Convert.ToString(Eval("Product_Id")))%>' RepeatColumns="1" RepeatLayout="Flow"> <ItemTemplate> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="spc_tab_hed_bg spc_hed_txt lm5 tm2 bm3"> <asp:Label ID="LblType" runat="server" Text='<%# Eval("TypeName", "{0}") %>'></asp:Label> </td> <td width="380" class="spc_tab_hed_bg"> &nbsp; </td> </tr> <tr> <td align="left" class="lm5 tm2 bm3"> <asp:Label ID="LblData" runat="server" Text='<%# Eval("Name", "{0}") %>'></asp:Label> </td> <td align="center" class=" tm2 bm3"> <a href='<%# "DownloadFile.aspx?Product_Id=" + DataBinder.Eval(Container.DataItem,"Product_Id") %>' > <img src="images/downloads_ht.jpg" width="11" height="11" border="0" /> </a> <%--<asp:ImageButton ID="ImageButton1" ImageUrl="images/downloads_ht.jpg" runat="server" OnClick="ImageButton1_Click1" />--%> </td> </tr> </table> </ItemTemplate> </asp:DataList> I tried more to solve this problem but I cannot please if any one has solve for this proplem please sent me thank you kareem saad programmer MCTS,MCPD Toshiba Company Egypt

    Read the article

  • Optimal storage of data structure for fast lookup and persistence

    - by Mikael Svenson
    Scenario I have the following methods: public void AddItemSecurity(int itemId, int[] userIds) public int[] GetValidItemIds(int userId) Initially I'm thinking storage on the form: itemId -> userId, userId, userId and userId -> itemId, itemId, itemId AddItemSecurity is based on how I get data from a third party API, GetValidItemIds is how I want to use it at runtime. There are potentially 2000 users and 10 million items. Item id's are on the form: 2007123456, 2010001234 (10 digits where first four represent the year). AddItemSecurity does not have to perform super fast, but GetValidIds needs to be subsecond. Also, if there is an update on an existing itemId I need to remove that itemId for users no longer in the list. I'm trying to think about how I should store this in an optimal fashion. Preferably on disk (with caching), but I want the code maintainable and clean. If the item id's had started at 0, I thought about creating a byte array the length of MaxItemId / 8 for each user, and set a true/false bit if the item was present or not. That would limit the array length to little over 1mb per user and give fast lookups as well as an easy way to update the list per user. By persisting this as Memory Mapped Files with the .Net 4 framework I think I would get decent caching as well (if the machine has enough RAM) without implementing caching logic myself. Parsing the id, stripping out the year, and store an array per year could be a solution. The ItemId - UserId[] list can be serialized directly to disk and read/write with a normal FileStream in order to persist the list and diff it when there are changes. Each time a new user is added all the lists have to updated as well, but this can be done nightly. Question Should I continue to try out this approach, or are there other paths which should be explored as well? I'm thinking SQL server will not perform fast enough, and it would give an overhead (at least if it's hosted on a different server), but my assumptions might be wrong. Any thought or insights on the matter is appreciated. And I want to try to solve it without adding too much hardware :) [Update 2010-03-31] I have now tested with SQL server 2008 under the following conditions. Table with two columns (userid,itemid) both are Int Clustered index on the two columns Added ~800.000 items for 180 users - Total of 144 million rows Allocated 4gb ram for SQL server Dual Core 2.66ghz laptop SSD disk Use a SqlDataReader to read all itemid's into a List Loop over all users If I run one thread it averages on 0.2 seconds. When I add a second thread it goes up to 0.4 seconds, which is still ok. From there on the results are decreasing. Adding a third thread brings alot of the queries up to 2 seonds. A forth thread, up to 4 seconds, a fifth spikes some of the queries up to 50 seconds. The CPU is roofing while this is going on, even on one thread. My test app takes some due to the speedy loop, and sql the rest. Which leads me to the conclusion that it won't scale very well. At least not on my tested hardware. Are there ways to optimize the database, say storing an array of int's per user instead of one record per item. But this makes it harder to remove items.

    Read the article

  • Unable to connect SQL Server instance from Visual Studio 2008 Version 9.0

    - by salvationishere
    I am getting the below error from VS on an 32-bit XP Professional server even though I set Tools-Options-Database Tools-Data Connections to "SIDEKICK", which is the name of my computer. In other words SIDEKICK should default to the full SQLSERVER. In other words, I want VS to use SQLSERVER instead of SQLSERVER EXPRESS. And I can clearly see my database both from VS in the Server Explorer and also in SSMS 2008. Furthermore, I can view the tables of this database in Server Explorer from VS. I do not get any build errors. And it looks like all of the naming is consistent in my web.config file. I am developing my website according to a Microsoft tutorial, so I should not be getting an error. Yet I get the following exception when I run this code below: CreateAccounts.aspx.cs file protected void CreateAccountButton_Click(object sender, EventArgs e) { MembershipCreateStatus createStatus; //This line below is where the exception occurs MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus); And here is what the exception looks like: System.Web.HttpException was unhandled by user code Message="Unable to connect to SQL Server database." Source="System.Web" ErrorCode=-2147467259 StackTrace: at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) at System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString) at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) at System.Web.Security.SqlMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, MembershipCreateStatus& status) at Membership_CreatingUserAccounts.CreateAccountButton_Click(Object sender, EventArgs e) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\WebSite2\Membership\CreatingUserAccounts.aspx.cs:line 24 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException: System.Web.HttpException Message="Unable to connect to SQL Server database." Source="System.Web" ErrorCode=-2147467259 StackTrace: at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) InnerException: System.Data.SqlClient.SqlException Message="The user instance login flag is not supported on this version of SQL Server. The connection will be closed." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=14 LineNumber=65536 Number=18493 Procedure="" Server="." State=1 StackTrace: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) InnerException: The web.config connection string looks like: <connectionStrings> <add name="SecurityTutorialsConnectionString" connectionString="data source=.;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|SecurityTutorialsDatabase3.mdf;User Instance=true" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <membership defaultProvider="SecurityTutorialsSqlMembershipProvider"> <providers> <add name="SecurityTutorialsSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SecurityTutorialsConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="SecurityTutorials" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/> </providers> </membership>

    Read the article

  • About global.asax and the events there

    - by eski
    So what i'm trying to understand is the whole global.asax events. I doing a simple counter that records website visits. I am using MSSQL. Basicly i have two ints. totalNumberOfUsers - The total visist from begining. currentNumberOfUsers - Total of users viewing the site at the moment. So the way i understand global.asax events is that every time someone comes to the site "Session_Start" is fired once. So once per user. "Application_Start" is fired only once the first time someone comes to the site. Going with this i have my global.asax file here. <script runat="server"> string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString; void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application.Lock(); Application["currentNumberOfUsers"] = 0; Application.UnLock(); string sql = "Select c_hit from v_counter where (id=1)"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); cmd.Connection.Open(); cmd.ExecuteNonQuery(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Application.Lock(); Application["totalNumberOfUsers"] = reader.GetInt32(0); Application.UnLock(); } reader.Close(); cmd.Connection.Close(); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["totalNumberOfUsers"] = (int)Application["totalNumberOfUsers"] + 1; Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] + 1; Application.UnLock(); string sql = "UPDATE v_counter SET c_hit = @hit WHERE c_type = 'totalNumberOfUsers'"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); SqlParameter hit = new SqlParameter("@hit", SqlDbType.Int); hit.Value = Application["totalNumberOfUsers"]; cmd.Parameters.Add(hit); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] - 1; Application.UnLock(); } </script> In the page_load i have this protected void Page_Load(object sender, EventArgs e) { l_current.Text = Application["currentNumberOfUsers"].ToString(); l_total.Text = Application["totalNumberOfUsers"].ToString(); } So if i understand this right, every time someone comes to the site both the currentNumberOfUsers and totalNumberOfUsers are incremented with 1. But when the session is over the currentNumberOfUsers is decremented with 1. If i go to the site with 3 types of browsers with the same computer i should have 3 in hits on both counters. Doing this again after hours i should have 3 in current and 6 in total, right ? The way its working right now is the current goes up to 2 and the total is incremented on every postback on IE and Chrome but not on firefox. And one last thing, is this the same thing ? Application["value"] = 0; value = Application["value"] //OR Application.Set("Value", 0); Value = Application.Get("Value");

    Read the article

  • Data adapter not filling my dataset

    - by Doug Ancil
    I have the following code: Imports System.Data.SqlClient Public Class Main Protected WithEvents DataGridView1 As DataGridView Dim instForm2 As New Exceptions Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startpayrollButton.Click Dim ssql As String = "select MAX(payrolldate) AS [payrolldate], " & _ "dateadd(dd, ((datediff(dd, '17530107', MAX(payrolldate))/7)*7)+7, '17530107') AS [Sunday]" & _ "from dbo.payroll" & _ " where payrollran = 'no'" Dim oCmd As System.Data.SqlClient.SqlCommand Dim oDr As System.Data.SqlClient.SqlDataReader oCmd = New System.Data.SqlClient.SqlCommand Try With oCmd .Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx") .Connection.Open() .CommandType = CommandType.Text .CommandText = ssql oDr = .ExecuteReader() End With If oDr.Read Then payperiodstartdate = oDr.GetDateTime(1) payperiodenddate = payperiodstartdate.AddSeconds(604799) Dim ButtonDialogResult As DialogResult ButtonDialogResult = MessageBox.Show(" The Next Payroll Start Date is: " & payperiodstartdate.ToString() & System.Environment.NewLine & " Through End Date: " & payperiodenddate.ToString()) If ButtonDialogResult = Windows.Forms.DialogResult.OK Then exceptionsButton.Enabled = True startpayrollButton.Enabled = False End If End If oDr.Close() oCmd.Connection.Close() Catch ex As Exception MessageBox.Show(ex.Message) oCmd.Connection.Close() End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click Dim connection As System.Data.SqlClient.SqlConnection Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx" Dim ds As New DataSet Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration INTO scratchpad3" & _ " FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber" & _ " where [Exceptions].exceptiondate between @payperiodstartdate and @payperiodenddate" & _ " GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," & _ " [Exceptions].code, [Exceptions].exceptiondate" connection = New SqlConnection(connectionString) connection.Open() Dim _CMD As SqlCommand = New SqlCommand(_sql, connection) _CMD.Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate) _CMD.Parameters.AddWithValue("@payperiodenddate", payperiodenddate) adapter.SelectCommand = _CMD Try adapter.Fill(ds) If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then 'it's empty MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data") connection.Close() Exceptions.saveButton.Enabled = False Exceptions.Hide() Else connection.Close() End If Catch ex As Exception MessageBox.Show(ex.ToString) connection.Close() End Try Exceptions.Show() End Sub Private Sub payrollButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollButton.Click Payrollfinal.Show() End Sub End Class and when I run my program and press this button Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click I have my date range within a time that I know that my dataset should produce a result, but when I put a line break in my code here: adapter.Fill(ds) and look at it in debug, I show a table value of 0. If I run the same query that I have to produce these results in sql analyser, I see 1 result. Can someone see why my query on my form produces a different result than the sql analyser does? Also here is my schema for my two tables: Exceptions employeenumber varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS exceptiondate datetime no 8 yes (n/a) (n/a) NULL starttime datetime no 8 yes (n/a) (n/a) NULL endtime datetime no 8 yes (n/a) (n/a) NULL duration varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS code varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS approvedby varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS approved varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS time timestamp no 8 yes (n/a) (n/a) NULL employees employeenumber varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS name varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS initials varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS loginname1 varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS

    Read the article

  • Web Services c#, Sending notifications Clients

    - by Diode
    I want to send a notification (say a string) to subscribers(subscribers ip addresses are in a database on the server side) by calling another method. when ever I call that method the output becomes error-some. [WebMethod] public string GetGroupPath(string emailAddress, string password, string ipAddress) { //SqlDataAdapter dbadapter = null; DataSet returnDS = new DataSet(); string groupName = null; string groupPath = null; SqlConnection dbconn = new SqlConnection("Server = localhost;Database=server;User ID = admin;Password = password;Trusted_Connection=false;"); dbconn.Open(); SqlCommand cmd = new SqlCommand(); string getGroupName = "select users.groupname from users where emailaddress = "+"'"+ emailAddress+"'"+ " and "+ "users.password = " + "'" +password+"'"; cmd.CommandText = getGroupName; cmd.Connection = dbconn; SqlDataReader reader = null; try { reader = cmd.ExecuteReader(); while (reader.Read()) { groupName = reader["groupname"].ToString(); } } catch (Exception) { groupPath = "Invalied"; } dbconn.Close(); dbconn.Open(); if (groupName != null) { string getPath = "select groups.grouppath from groups where groupname = " + "'" + groupName + "'"; cmd.CommandText = getPath; cmd.Connection = dbconn; try { reader = cmd.ExecuteReader(); while (reader.Read()) { groupPath = reader["grouppath"].ToString(); } } catch { groupPath = "Invalied"; } } else groupPath = "Invalied"; dbconn.Close(); if (groupPath != "Invalied") { dbconn.Open(); string getPath = "update users set users.ipaddress = "+"'"+ipAddress+"'"+" where users.emailaddress = " + "'" + emailAddress + "'"; cmd.CommandText = getPath; cmd.Connection = dbconn; cmd.ExecuteNonQuery(); dbconn.Close(); } NotifyUsers(); //NotifyUsers nu = new NotifyUsers(); //List<string> ipList = new List<string>(); //ipList.Add("192.168.56.1"); //nu.Notify(); return groupPath; } private void NotifyUsers() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] ipb = Encoding.ASCII.GetBytes("255.255.255.255"); IPAddress ipAddress = new IPAddress(ipb); IPEndPoint endPoint = new IPEndPoint(ipAddress, 15000); string notification = "new_update"; byte[] sendBuffer = Encoding.ASCII.GetBytes(notification); sock.SendTo(sendBuffer, endPoint); sock.Close(); } This is what has to be basically done. in the server side I have a listening thread and it gets notification when the server sends data( assume for now the database contains client ip address). then ever I call the web method it gives a error "invalid IPAddress" atline byte[] ipb = Encoding.ASCII.GetBytes("255.255.255.255"); thank you :) since this is my first ever post please be kind enough to give me a better feedback too :) thaks

    Read the article

  • System.Data.SqlClient.SqlException: Must declare the scalar variable "@"

    - by Owala Wilson
    Haloo everyone...I am new to asp.net and I have been trying to query one table, and if the value returns true execute another query. here is my code: protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString); SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString); int amounts = Convert.ToInt32(InstallmentPaidBox.Text) + Convert.ToInt32(InterestPaid.Text) + Convert.ToInt32(PenaltyPaid.Text); int loans = Convert.ToInt32(PrincipalPaid.Text) + Convert.ToInt32(InterestPaid.Text); con.Open(); DateTime date = Convert.ToDateTime(DateOfProcessing.Text); int month1 = Convert.ToInt32(date.Month); int year1 = Convert.ToInt32(date.Year); SqlCommand a = new SqlCommand("Select Date,max(Amount)as Amount from Minimum_Amount group by Date",con); SqlDataReader sq = a.ExecuteReader(); while (sq.Read()) { DateTime date2 = Convert.ToDateTime(sq["Date"]); int month2 = Convert.ToInt32(date2.Month); int year2 = Convert.ToInt32(date2.Year); if (month1 == month2 && year1 == year2) { int amount = Convert.ToInt32(sq["Amount"]); string scrip = "<script>alert('Data Successfully Added')</script>"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Added", scrip); int areas = amount - Convert.ToInt32(InstallmentPaidBox.Text); int forwarded = Convert.ToInt32(BalanceBroughtTextBox.Text) + Convert.ToInt32(InstallmentPaidBox.Text); if (firsttime.Checked) { int balance = areas + Convert.ToInt32(PenaltyDue.Text) + Convert.ToInt32(InterestDue.Text); SqlCommand cmd = new SqlCommand("insert into Cash_Position(Member_No,Welfare_Amount, BFWD,Amount,Installment_Paid,Loan_Repayment,Principal_Payment,Interest_Paid,Interest_Due,Loan_Balance,Penalty_Paid,Penalty_Due,Installment_Arrears,CFWD,Balance_Due,Date_Prepared,Prepared_By) values(@a,@b,@c,@d,@e,@)f,@g,@h,@i,@j,@k,@l,@m,@n,@o,@p,@q", con); cmd.Parameters.Add("@a", SqlDbType.Int).Value = MemberNumberTextBox.Text; cmd.Parameters.Add("@b", SqlDbType.Int).Value = WelfareAmount.Text; cmd.Parameters.Add("@c", SqlDbType.Int).Value = BalanceBroughtTextBox.Text; cmd.Parameters.Add("@d", SqlDbType.Int).Value = amounts; cmd.Parameters.Add("@e", SqlDbType.Int).Value = InstallmentPaidBox.Text; cmd.Parameters.Add("@f", SqlDbType.Int).Value = loans; cmd.Parameters.Add("@g", SqlDbType.Int).Value = PrincipalPaid.Text; cmd.Parameters.Add("@h", SqlDbType.Int).Value = InterestDue.Text; cmd.Parameters.Add("@i", SqlDbType.Int).Value = InterestDue.Text; cmd.Parameters.Add("@j", SqlDbType.Int).Value = 0; cmd.Parameters.Add("@k", SqlDbType.Int).Value = PenaltyPaid.Text; cmd.Parameters.Add("@l", SqlDbType.Int).Value = PenaltyDue.Text; cmd.Parameters.Add("@m", SqlDbType.Int).Value = areas; cmd.Parameters.Add("@n", SqlDbType.Int).Value = forwarded; cmd.Parameters.Add("@o", SqlDbType.Int).Value = balance; cmd.Parameters.Add("@p", SqlDbType.Date).Value = date; cmd.Parameters.Add("@q", SqlDbType.Text).Value = PreparedBy.Text; int rows = cmd.ExecuteNonQuery(); con.Close();

    Read the article

  • Include weather information in ASP.Net site from weather.com services

    - by sreejukg
    In this article, I am going to demonstrate how you can use the XMLOAP services (referred as XOAP from here onwards) provided by weather.com to display the weather information in your website. The XOAP services are available to be used for free of charge, provided you are comply with requirements from weather.com. I am writing this article from a technical point of view. If you are planning to use weather.com XOAP services in your application, please refer to the terms and conditions from weather.com website. In order to start using the XOAP services, you need to sign up the XOAP datafeed. The signing process is simple, you simply browse the url http://www.weather.com/services/xmloap.html. The URL looks similar to the following. Click on the sign up button, you will reach the registration page. Here you need to specify the site name you need to use this feed for. The form looks similar to the following. Once you fill all the mandatory information, click on save and continue button. That’s it. The registration is over. You will receive an email that contains your partner id, license key and SDK. The SDK available in a zipped format, contains the terms of use and documentation about the services available. Other than this the SDK includes the logos and icons required to display the weather information. As per the SDK, currently there are 2 types of information available through XOAP. These services are Current Conditions for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Hourly Five-Day Forecast (today + 4 additional forecast days in consecutive order beginning with tomorrow) for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Three Times Daily The SDK provides detailed information about the fields included in response of each service. Additionally there is a refresh rate that you need to comply with. As per the SDK, the refresh rate means the following “Refresh Rate” shall mean the maximum frequency with which you may call the XML Feed for a given LocID requesting a data set for that LocID. During the time period in between refresh periods the data must be cached by you either in the memory on your servers or in Your Desktop Application. About the Services Weather.com will provide you with access to the XML Feed over the Internet through the hostname xoap.weather.com. The weather data from the XML feed must be requested for a specific location. So you need a location ID (LOC ID). The XML feed work with 2 types of location IDs. First one is with City Identifiers and second one is using 5 Digit US postal codes. If you do not know your location ID, don’t worry, there is a location id search service available for you to retrieve the location id from city name. Since I am a resident in the Kingdom of Bahrain, I am going to retrieve the weather information for Manama(the capital of Bahrain) . In order to get the location ID for Manama, type the following URL in your address bar. http://xoap.weather.com/search/search?where=manama I got the following XML output. <?xml version="1.0" encoding="UTF-8"?> <!-- This document is intended only for use by authorized licensees of The –> <!-- Weather Channel. Unauthorized use is prohibited. Copyright 1995-2011, –> <!-- The Weather Channel Interactive, Inc. All Rights Reserved. –> <search ver="3.0">       <loc id="BAXX0001" type="1">Al Manama, Bahrain</loc> </search> You can try this with any city name, if the city is available, it will return the location id, and otherwise, it will return nothing. In order to get the weather information, from XOAP,  you need to pass certain parameters to the XOAP service. A brief about the parameters are as follows. Please refer SDK for more details. Parameter name Possible Value cc Optional, if you include this, the current condition will be returned. Value can be anything, as it will be ignored e.g. cc=* dayf If you want the forecast for 5 days, specify dayf=5 This is optional iink Value should be XOAP par Your partner id. You can find this in your registration email from weather.com prod Value should be XOAP key The license key assigned to you. This will be available in the registration email unit s or m (standard or matric or you can think of Celsius/Fahrenheit) this is optional field, if not specified the unit will be standard(s) The URL host for the XOAP service is http://xoap.weather.com. So for my purpose, I need the following request to be made to access the XOAP services. http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=*********&key=************** (The ***** to be replaced with the corresponding alternatives) The response XML have a root element “weather”. Under the root element, it has the following sections <head> - the meta data information about the weather results returned. <loc> - the location data block that provides, the information about the location for which the wheather data is retrieved. <lnks> - the 4 promotional links you need to place along with the weather display. Additional to these 4 links, there should be another link with weather channel logo to the home page of weather.com. <cc> - the current condition data. This element will be there only if you specify the cc element in the request. <dayf> - the forcast data as you specified. This element will be there only if you specify the dayf in the request. In this walkthrough, I am going to capture the weather information for Manama (Location ID: BAXX0001). You need 2 applications to display weather information in your website. A Console application that retrieves data from the XMLOAP and store in the SQL Server database (or any data store as you prefer).This application will be scheduled to execute in every 25 minutes using windows task scheduler, so that we can comply with the refresh rate. A web application that display data from the SQL Server database Retrieve the Weather from XOAP I have created a console application named, Weather Service. I created a SQL server database, with the following columns. I named the table as tblweather. You are free to choose any name. Column name Description lastUpdated Datetime, this is the last time when the weather data is updated. This is the time of the service running TemparatureDateTime The date and time returned by XML feed Temparature The temperature returned by the XML feed. TemparatureUnit The unit of the temperature returned by the XML feed iconId The id of the icon to be used. Currently 48 icons from 0 to 47 are available. WeatherDescription The Weather Description Phrase returned by the feed. Link1url The url to the first promo link Link1Text The text for the first promo link Link2url The url to the second promo link Link2Text The text for the second promo link Link3url The url to the third promo link Link3Text The text for the third promo link Link4url The url to the fourth promo link Link4Text The text for the fourth promo link Every time when the service runs, the application will update the database columns from the XOAP data feed. When the application starts, It is going to get the data as XML from the url. This demonstration uses LINQ to extract the necessary data from the fetched XML. The following are the code segment for extracting data from the weather XML using LINQ. // first, create an instance of the XDocument class with the XOAP URL. replace **** with the corresponding values. XDocument weather = XDocument.Load("http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=***********&key=c*********"); // construct a query using LINQ var feedResult = from item in weather.Descendants() select new { unit = item.Element("head").Element("ut").Value, temp = item.Element("cc").Element("tmp").Value, tempDate = item.Element("cc").Element("lsup").Value, iconId = item.Element("cc").Element("icon").Value, description = item.Element("cc").Element("t").Value, links = from link in item.Elements("lnks").Elements("link") select new { url = link.Element("l").Value, text = link.Element("t").Value } }; // Load the root node to a variable, you may use foreach construct instead. var item1 = feedResult.First(); *If you want to learn more about LINQ and XML, read this nice blog from Scott GU. http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx Now you have all the required values in item1. For e.g. if you want to get the temperature, use item1.temp; Now I just need to execute an SQL query against the database. See the connection part. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { string strSql = @"update tblweather set lastupdated=getdate(), temparatureDateTime = @temparatureDateTime, temparature=@temparature, temparatureUnit=@temparatureUnit, iconId = @iconId, description=@description, link1url=@link1url, link1text=@link1text, link2url=@link2url, link2text=@link2text,link3url=@link3url, link3text=@link3text,link4url=@link4url, link4text=@link4text"; SqlCommand comm = new SqlCommand(strSql, conn); comm.Parameters.AddWithValue("temparatureDateTime", item1.tempDate); comm.Parameters.AddWithValue("temparature", item1.temp); comm.Parameters.AddWithValue("temparatureUnit", item1.unit); comm.Parameters.AddWithValue("description", item1.description); comm.Parameters.AddWithValue("iconId", item1.iconId); var lstLinks = item1.links; comm.Parameters.AddWithValue("link1url", lstLinks.ElementAt(0).url); comm.Parameters.AddWithValue("link1text", lstLinks.ElementAt(0).text); comm.Parameters.AddWithValue("link2url", lstLinks.ElementAt(1).url); comm.Parameters.AddWithValue("link2text", lstLinks.ElementAt(1).text); comm.Parameters.AddWithValue("link3url", lstLinks.ElementAt(2).url); comm.Parameters.AddWithValue("link3text", lstLinks.ElementAt(2).text); comm.Parameters.AddWithValue("link4url", lstLinks.ElementAt(3).url); comm.Parameters.AddWithValue("link4text", lstLinks.ElementAt(3).text); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); Console.WriteLine("database updated"); } Now click ctrl + f5 to run the service. I got the following output Check your database and make sure, the data is updated with the latest information from the service. (Make sure you inserted one row in the database by entering some values before executing the service. Otherwise you need to modify your application code to count the rows and conditionally perform insert/update query) Display the Weather information in ASP.Net page Now you got all the data in the database. You just need to create a web application and display the data from the database. I created a new ASP.Net web application with a default.aspx page. In order to comply with the terms of weather.com, You need to use Weather.com logo along with the weather display. You can find the necessary logos to use under the folder “logos” in the SDK. Additionally copy any of the icon set from the folder “icons” to your web application. I used the 93x93 icon set. You are free to use any other sizes available. The design view of the page in VS2010 looks similar to the following. The page contains a heading, an image control (for displaying the weather icon), 2 label controls (for displaying temperature and weather description), 4 hyperlinks (for displaying the 4 promo links returned by the XOAP service) and weather.com logo with hyperlink to the weather.com home page. I am going to write code that will update the values of these controls from the values stored in the database by the service application as mentioned in the previous step. Go to the code behind file for the webpage, enter the following code under Page_Load event handler. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { SqlCommand comm = new SqlCommand("select top 1 * from tblweather", conn); conn.Open(); SqlDataReader reader = comm.ExecuteReader(); if (reader.Read()) { lblTemparature.Text = reader["temparature"].ToString() + "&deg;" + reader["temparatureUnit"].ToString(); lblWeatherDescription.Text = reader["description"].ToString(); imgWeather.ImageUrl = "icons/" + reader["iconId"].ToString() + ".png"; lnk1.Text = reader["link1text"].ToString(); lnk1.NavigateUrl = reader["link1url"].ToString(); lnk2.Text = reader["link2text"].ToString(); lnk2.NavigateUrl = reader["link2url"].ToString(); lnk3.Text = reader["link3text"].ToString(); lnk3.NavigateUrl = reader["link3url"].ToString(); lnk4.Text = reader["link4text"].ToString(); lnk4.NavigateUrl = reader["link4url"].ToString(); } conn.Close(); } Press ctrl + f5 to run the page. You will see the following output. That’s it. You need to configure the console application to run every 25 minutes so that the database is updated. Also you can fetch the forecast information and store those in the database, and then retrieve it later in your web page. Since the data resides in your database, you have the full control over your display. You need to make sure your website comply with weather.com license requirements. If you want to get the source code of this walkthrough through the application, post your email address below. Hope you enjoy the reading.

    Read the article

  • CodePlex Daily Summary for Sunday, June 05, 2011

    CodePlex Daily Summary for Sunday, June 05, 2011Popular ReleasesSizeOnDisk: 1.0.8.1: Toolbar: Show total of selected folder and hard drive usage of the entire disk Fix: Command binding do not work Execution State Toolbar state by selection Progress task barEnhSim: EnhSim 2.4.6 BETA: 2.4.6 BETAThis release supports WoW patch 4.1 at level 85 To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Added in the proper...patterns & practices: Project Silk: Project Silk Community Drop 10 - June 3, 2011: Changes from previous drop: Many code changes: please see the readme.mht for details. New "Application Notifications" chapter. Updated "Server-Side Implementation" chapter. Guidance Chapters Ready for Review The Word documents for the chapters are included with the source code in addition to the CHM to help you provide feedback. The PDF is provided as a separate download for your convenience. Installation Overview To install and run the reference implementation, you must perform the fol...Claims Based Identity & Access Control Guide: Release Candidate: Highlights of this release This is the release candidate drop of the new "Claims Identity Guide" edition. In this release you will find: All code samples, including all ACS v2: ACS as a Federation Provider - Showing authentication with LiveID, Google, etc. ACS as a FP with Multiple Business Partners. ACS and REST endpoints. Using a WP7 client with REST endpoints. All ACS specific chapters. Two new chapters on SharePoint (SSO and Federation) All revised v1 chapters We are now ...Media Companion: MC 3.404b Weekly: Extract the entire archive to a folder which has user access rights, eg desktop, documents etc. Refer to the documentation on this site for the Installation & Setup Guide Important! *** Due to an issue where the date added & the full genre information was not being read into the Movie cache, it is highly recommended that you perform a Rebuild Movies when first running this latest version. This will read in the information from the nfo's & repopulate the cache used by MC during operation. Fi...Terraria Map Generator: TerrariaMapTool 1.0.0.4 Beta: 1) Fixed the generated map.html file so that the file:/// is included in the base path. 2) Added the ability to use parallelization during generation. This will cause the program to use as many threads as there are physical cores. 3) Fixed some background overdraw.DotRas: DotRas v1.2 (Version 1.2.4168): This release includes compiled (and signed) versions of the binaries, PDBs, CHM help documentation, along with both C# and VB.NET examples. Please don't forget to rate the release! If you find a bug, please open a work item and give as much description as possible. Stack traces, which operating system(s) you're targeting, and build type is also very helpful for bug hunting. If you find something you believe to be a bug but are not sure, create a new discussion on the discussions board. Thank...Caliburn Micro: WPF, Silverlight and WP7 made easy.: Caliburn.Micro v1.1 RTW: Download ContentsDebug and Release Assemblies Samples Changes.txt License.txt Release Highlights For WP7A new Tombstoning API based on ideas from Fluent NHibernate A new Launcher/Chooser API Strongly typed Navigation SimpleContainer included The full phone lifecycle is made easy to work with ie. we figure out whether your app is actually Resurrecting or just Continuing for you For WPFSupport for the Client Profile Better support for WinForms integration All PlatformsA power...VidCoder: 0.9.1: Added color coding to the Log window. Errors are highlighted in red, HandBrake logs are in black and VidCoder logs are in dark blue. Moved enqueue button to the right with the other control buttons. Added logic to report failures when errors are logged during the encode or when the encode finishes prematurely. Added Copy button to Log window. Adjusted audio track selection box to always show the full track name. Changed encode job progress bar to also be colored yellow when the enco...AutoLoL: AutoLoL v2.0.1: - Fixed a small bug in Auto Login - Fixed the updaterEPPlus-Create advanced Excel 2007 spreadsheets on the server: EPPlus 2.9.0.1: EPPlus-Create advanced Excel 2007 spreadsheets on the server This version has been updated to .Net Framework 3.5 New Features Data Validation. PivotTables (Basic functionalliy...) Support for worksheet data sources. Column, Row, Page and Data fields. Date and Numeric grouping Build in styles. ...and more And some minor new features... Ranges Text-Property|Get the formated value AutofitColumns-method to set the column width from the content of the range LoadFromCollection-metho...jQuery ASP.Net MVC Controls: Version 1.4.0.0: Version 1.4.0.0 contains the following additions: Upgraded to MVC 3.0 Upgraded to jQuery 1.6.1 (Though the project supports all jQuery version from 1.4.x onwards) Upgraded to jqGrid 3.8 Better Razor View-Engine support Better Pager support, includes support for custom pagers Added jqGrid toolbar buttons support Search module refactored, with full suport for multiple filters and ordering And Code cleanup, bug-fixes and better controller configuration support.Nearforums - ASP.NET MVC forum engine: Nearforums v6.0: Version 6.0 of Nearforums, the ASP.NET MVC Forum Engine, containing new features: Authentication using Membership Provider for SQL Server and MySql Spam prevention: Flood Control Moderation: Flag messages Content management: Pages: Create pages (about us/contact/texts) through web administration Allow nearforums to run as an IIS subapp Migrated Facebook Connect to OAuth 2.0 Visit the project Roadmap for more details.NetOffice - The easiest way to use Office in .NET: NetOffice Release 0.8b: Changes: - fix critical issue 15922(AccessViolationException) once and for all ...update is strongly recommended Known Issues: - some addin ribbon examples has a COM Register function with missing codebase entry(win32 registry) ...the problem is only affected to c# examples. fixed in latest source code. NetOffice\ReleaseTags\NetOffice Release 0.8.rar Includes: - Runtime Binaries and Source Code for .NET Framework:......v2.0, v3.0, v3.5, v4.0 - Tutorials in C# and VB.Net:...................Serviio for Windows Home Server: Beta Release 0.5.2.0: Ready for widespread beta. Synchronized build number to Serviio version to avoid confusion.AcDown????? - Anime&Comic Downloader: AcDown????? v3.0 Beta4: ??AcDown?????????????,??????????????,????、????。?????Acfun????? ????32??64? Windows XP/Vista/7 ????????????? ??:????????Windows XP???,?????????.NET Framework 2.0???(x86)?.NET Framework 2.0???(x64),?????"?????????"??? ??v3.0 Beta4 2011-5-31?? ???Bilibili.us????? ???? ?? ???"????" ???Bilibili.us??? ??????? ?? ??????? ?? ???????? ?? ?? ???Bilibili.us?????(??????????????????) ??????(6.cn)?????(????) ?? ?????Acfun?????????? ?????????????? ???QQ???????? ????????????Discussion...CodeCopy Auto Code Converter: Code Copy v0.1: Full add-in, setup project source code and setup fileWordpress Theme 'Windows Metro': v1.00.0017: v1.00.0017 Dies ist eine Vorab-Version aus der Entwickler-Phase. This is a preview version from the development phase.TerrariViewer: TerrariViewer v2.4.1: Added Piggy Bank editor and fixed some minor bugs.Kooboo CMS: Kooboo CMS 3.02: Updated the Kooboo_CMS.zip at 2011-06-02 11:44 GMT 1.Fixed: Adding data rule issue on page. 2.Fixed: Caching issue for higher performance. Updated the Kooboo_CMS.zip at 2011-06-01 10:00 GMT 1. Fixed the published package throwed a compile error under WebSite mode. 2. Fixed the ContentHelper.NewMediaFolderObject return TextFolder issue. 3. Shorten the name of ContentHelper API. NewMediaFolderObject=>MediaFolder, NewTextFolderObject=> TextFolder, NewSchemaObject=>Schema. Also update the C...New ProjectsbuddyAgent: buddyAgent is a Classified PortalDataReaderMapping: use linq expression make mapping sqldatareader to DTO model easyForeign eXchange Center: Foreign eXchange CenterGoogleAuthCLONE: Use this like the Google Authenticator you may have on your Android device to interact with Google's Two Factor Authentication scheme. This allows you to log into Google without having to whip out your phone. Stores account information securely!Grammar and Spell Checking Plugin for Windows Live Writer: This project is a spelling and grammar checker plugin for Windows Live Writer. It uses the "After the Deadline" web service to provide advanced grammar checking abilities.GUNDEMAS: Gundemas.comInstantMods: LolLig4 => Análise e Desenvolvimento de Sistemas: Beta teste App_SERVERLight Time Sheet: Silverlight Time SheetMort8088s XmlHelper: XmlHelper makes it easier for developers to create and read data in XML documents by condensing common tasks into a simple static helper class. XmlHelper's developed in c#. Feel free to suggest new methods or better ways to achieve the existing methods.NeuroForecast: This project is designed to study neural network technologies on the example of predicting currency quotes.Orchard Forums: a forums moduleRules Engine: Rules Engine is a C# project that makes it easier for developers to define business rules on domain objects without coupling the domain object to the business rule. The rules engine supports cross-field validation and conditional validation. Rules are interface-based and are easily extensible. Rules can be added using a fluent interface.Super Byte: Super Byte makes it easier for everyone to use your computer .You'll no longer have to strugle. We are always looking for new devlopers. It's developed in C#. Need a fast and reliable "Operating System"? Well SuperByte can give that to you. We have spent many hours of work to bring this project to you. Enjoy! Taygeta - The video shadering library: This library allows rendering YUV and RGB pixel formats using Direct3D 9 runtime. You can also apply shaders and add text, bitmap and line overlays.Test Driver Program: Testing driver programTowerDefense: ????,??ogre??YAPE: Yet Another Pacman Emulator.

    Read the article

  • ASP.NET Web Page Not Available

    - by hahuang65
    It's pretty difficult to show code for ASP.NET here, so I will try my best to describe my problem. I have a FileUploadControl and a Button that calls a function when it's clicked. It seems that the Button function works when there is nothing chosen for my FileUploadControl. However, when there is something chosen in the FileUploadControl (I have selected a file to upload), there is a problem when I click the button. It completely does not matter what the function does (it could just be writing to a label, even when it has nothing to do with the FileUploadControl). The error I get is: This webpage is not available. The webpage at http://localhost:2134/UploadMedia/Default.aspx might be temporarily down or it may have moved permanently to a new web address. I have searched on Google, and people seem to have had problems with this, but different causes from me. They have said that their ASP.NET Development Server port is actually different from their port in the address bar. This is not the case for me. Also, another problem people have had is with Use Dynamic Ports. I have tried both true and false. I have also tried different ports, and I have always gotten the same error. This is really driving me crazy because it doesn't matter what the code in the buttonFunction is, it doesn't work as long as there is something in the FileUploadControl. If there is nothing, it seems to work fine. Here is the code for the ASP.NET Controls: <asp:FileUpload id="FileUploadControl" runat="server" /> <asp:Button runat="server" id="UploadButton" text="Upload" OnClick="uploadClicked" /> <br /><br /> <asp:Label runat="server" id="StatusLabel" text="Upload status: " /> And this is the code for the button function: protected void uploadClicked(object sender, EventArgs e) { if (FileUploadControl.HasFile) { string filename = Path.GetFileName(FileUploadControl.FileName); //Check if the entered username already exists in the database. String sqlDupStmt = "Select songPath from Songs where songPath ='" + Server.MapPath("~/Uploads/") + filename + "'"; SqlConnection sqlDupConn = new SqlConnection(@"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True;"); SqlCommand sqlDupCmd = new SqlCommand(sqlDupStmt, sqlDupConn); sqlDupCmd.Connection.Open(); SqlDataReader sqlDupReader = sqlDupCmd.ExecuteReader(CommandBehavior.CloseConnection); if (sqlDupReader.Read()) { StatusLabel.Text = "Upload status: The file already exists."; sqlDupReader.Close(); } else { sqlDupReader.Close(); //See "How To Use DPAPI (Machine Store) from ASP.NET" for information about securely storing connection strings. String sqlStmt = "Insert into Songs values (@songpath);"; SqlConnection sqlConn = new SqlConnection(@"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True; uid=sa; pwd=password;"); SqlCommand cmd = new SqlCommand(sqlStmt, sqlConn); SqlParameter sqlParam = null; //Usage of Sql parameters also helps avoid SQL Injection attacks. sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 150); sqlParam.Value = Server.MapPath("~/Uploads/") + filename; //Attempt to add the song to the database. try { sqlConn.Open(); cmd.ExecuteNonQuery(); FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename); songList.Items.Add(filename); StatusLabel.Text = "Upload status: File uploaded!"; } catch (Exception ex) { StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } finally { sqlConn.Close(); } } } } But this buttonfunction provides the same results: protected void uploadClicked(object sender, EventArgs e) { StatusLabel.Text = "FooBar"; } Has anyone had this problem before, or might know what the cause is? Thanks!

    Read the article

  • Can't update textbox in TinyMCE

    - by Michael Tot Korsgaard
    I'm using TinyMCE, the text area is replaced with a TextBox, but when I try to update the database with the new text from my textbox, it wont update. Can anyone help me? My code looks like this <%@ Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Test_TinyMCE._default" ValidateRequest="false" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <script src="JavaScript/tiny_mce/tiny_mce.js" type="text/javascript"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode: "textareas", theme: "advanced", plugins: "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,pre view,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,no nbreaking,xhtmlxtras,template,wordcount,advlist,autosave", // Theme options theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_resizing: true, // Example content CSS (should be your site CSS) // using false to ensure that the default browser settings are used for best Accessibility // ACCESSIBILITY SETTINGS content_css: false, // Use browser preferred colors for dialogs. browser_preferred_colors: true, detect_highcontrast: true, // Drop lists for link/image/media/template dialogs template_external_list_url: "lists/template_list.js", external_link_list_url: "lists/link_list.js", external_image_list_url: "lists/image_list.js", media_external_list_url: "lists/media_list.js", // Style formats style_formats: [ { title: 'Bold text', inline: 'b' }, { title: 'Red text', inline: 'span', styles: { color: '#ff0000'} }, { title: 'Red header', block: 'h1', styles: { color: '#ff0000'} }, { title: 'Example 1', inline: 'span', classes: 'example1' }, { title: 'Example 2', inline: 'span', classes: 'example2' }, { title: 'Table styles' }, { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' } ], // Replace values for the template plugin template_replace_values: { username: "Some User", staffid: "991234" } }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox> <br /> <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Update</asp:LinkButton> </div> </asp:Content> My codebhind looks like this using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Test_TinyMCE { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { TextBox1.Text = Database.GetFirst().Text; } protected void LinkButton1_Click(object sender, EventArgs e) { Database.Update(Database.GetFirst().ID, TextBox1.Text); TextBox1.Text = Database.GetFirst().Text; } } } And finally the "Database" class im using looks like this using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data.SqlClient; namespace Test_TinyMCE { public class Database { public int ID { get; set; } public string Text { get; set; } public static void Update(int ID, string Text) { SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DatabaseConnection"]); connection.Open(); try { SqlCommand command = new SqlCommand("Update Text set Text=@text where ID=@id"); command.Connection = connection; command.Parameters.Add(new SqlParameter("id", ID)); command.Parameters.Add(new SqlParameter("text", Text)); command.ExecuteNonQuery(); } finally { connection.Close(); } } public static Database GetFirst() { SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DatabaseConnection"]); connection.Open(); try { SqlCommand command = new SqlCommand("Select Top 1 ID, Text from Text order by ID asc"); command.Connection = connection; SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { Database item = new Database(); item.ID = reader.GetInt32(0); item.Text = reader.GetString(1); return item; } else { return null; } } finally { connection.Close(); } } } } I really hope that someone out there can help me

    Read the article

  • C# SQL Parameter Errors in Loops

    - by jakesankey
    Please help me out with this. I have this small application to load txt files into a sql db and it works fine with sqlite. When I ported to SQL I started getting 'parameter already declared' errors.. If anyone can help me reorganize this code, it would be great! I need to get the parameter definitions outside of the loops or something.. using System; using System.Data; using System.Data.SQLite; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Data.SqlClient; namespace JohnDeereCMMDataParser { internal class Program { public static List<string> GetImportedFileList() { List<string> ImportedFiles = new List<string>(); using (SqlConnection connect = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { connect.Open(); using (SqlCommand fmd = connect.CreateCommand()) { fmd.CommandText = @"SELECT FileName FROM Import;"; fmd.CommandType = CommandType.Text; SqlDataReader r = fmd.ExecuteReader(); while (r.Read()) { ImportedFiles.Add(Convert.ToString(r["FileName"])); } } } return ImportedFiles; } private static void Main(string[] args) { using (SqlConnection con = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { con.Open(); using (SqlCommand insertCommand = con.CreateCommand()) { Console.WriteLine("Connecting to SQL server..."); SqlCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\", "R.txt*", SearchOption.AllDirectories); insertCommand.Parameters.Add(new SqlParameter("@FeatType", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@FeatName", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Value", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@OutOfTol", DbType.Decimal)); List<string> ImportedFiles = GetImportedFileList(); foreach (string file in files.Except(ImportedFiles)) { var FileNameExt1 = Path.GetFileName(file); cmdd.Parameters.Add(new SqlParameter("@FileExt", FileNameExt1)); cmdd.CommandText = @" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'Import')) BEGIN SELECT COUNT(*) FROM Import WHERE FileName = @FileExt; END"; int count = Convert.ToInt32(cmdd.ExecuteScalar()); con.Close(); con.Open(); if (count == 0) { Console.WriteLine("Parsing CMM data for SQL database... Please wait."); insertCommand.CommandText = @" INSERT INTO Import (FeatType, FeatName, Value, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Value, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; string FileNameExt = Path.GetFullPath(file); string RNumber = Path.GetFileNameWithoutExtension(file); string RNumberE = RNumber.Split('_')[0]; string RNumberD = RNumber.Split('_')[1]; string RNumberDate = RNumber.Split('_')[2]; DateTime dateTime = DateTime.ParseExact(RNumberDate, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SqlParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { SqlParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } } insertCommand.Parameters.Add(new SqlParameter("@PartNumber", RNumberE)); insertCommand.Parameters.Add(new SqlParameter("@CMMNumber", RNumberD)); insertCommand.Parameters.Add(new SqlParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SqlParameter("@FileName", FileNameExt)); // insertCommand.ExecuteNonQuery(); } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); } } } } FYI - the PartNumber, CMMNumber, Date, etc at the bottom are pulled from the file name and I need it in the table next to each respective record.

    Read the article

  • SQL error C# - Parameter already defined

    - by jakesankey
    Hey there. I have a c# application that parses txt files and imports the data from them into a sql db. I was using sqlite and am now working on porting it to sql server. It was working fine with sqlite but now with sql i am getting an error when it is processing the files. It added the first row of data to the db and then says "parameter @PartNumber has already been declared. Variable names must be unique within a batch or stored procedure". Here is my whole code and SQL table layout ... the error comes at the last insertCommand.ExecuteNonQuery() instance at the end of the code... SQL TABLE: CREATE TABLE Import ( RowId int PRIMARY KEY IDENTITY, PartNumber text, CMMNumber text, Date text, FeatType text, FeatName text, Value text, Actual text, Nominal text, Dev text, TolMin text, TolPlus text, OutOfTol text, FileName text ); CODE: using System; using System.Data; using System.Data.SQLite; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Data.SqlClient; namespace JohnDeereCMMDataParser { internal class Program { public static List<string> GetImportedFileList() { List<string> ImportedFiles = new List<string>(); using (SqlConnection connect = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { connect.Open(); using (SqlCommand fmd = connect.CreateCommand()) { fmd.CommandText = @"IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'Import')) BEGIN SELECT DISTINCT FileName FROM Import; END"; fmd.CommandType = CommandType.Text; SqlDataReader r = fmd.ExecuteReader(); while (r.Read()) { ImportedFiles.Add(Convert.ToString(r["FileName"])); } } } return ImportedFiles; } private static void Main(string[] args) { Console.Title = "John Deere CMM Data Parser"; Console.WriteLine("Preparing CMM Data Parser... done"); Console.WriteLine("Scanning for new CMM data... done"); Console.ForegroundColor = ConsoleColor.Gray; using (SqlConnection con = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { con.Open(); using (SqlCommand insertCommand = con.CreateCommand()) { SqlCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\", "R303717*.txt*", SearchOption.AllDirectories); List<string> ImportedFiles = GetImportedFileList(); foreach (string file in files.Except(ImportedFiles)) { string FileNameExt1 = Path.GetFileName(file); cmdd.CommandText = @" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'Import')) BEGIN SELECT COUNT(*) FROM Import WHERE FileName = @FileExt; END"; cmdd.Parameters.Add(new SqlParameter("@FileExt", FileNameExt1)); int count = Convert.ToInt32(cmdd.ExecuteScalar()); con.Close(); con.Open(); if (count == 0) { Console.WriteLine("Parsing CMM data for SQL database... Please wait."); insertCommand.CommandText = @" INSERT INTO Import (FeatType, FeatName, Value, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Value, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; insertCommand.Parameters.Add(new SqlParameter("@FeatType", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@FeatName", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Value", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@OutOfTol", DbType.Decimal)); string FileNameExt = Path.GetFullPath(file); string RNumber = Path.GetFileNameWithoutExtension(file); string RNumberE = RNumber.Split('_')[0]; string RNumberD = RNumber.Split('_')[1]; string RNumberDate = RNumber.Split('_')[2]; DateTime dateTime = DateTime.ParseExact(RNumberDate, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SqlParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { SqlParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } insertCommand.Parameters.Add(new SqlParameter("@PartNumber", RNumberE)); insertCommand.Parameters.Add(new SqlParameter("@CMMNumber", RNumberD)); insertCommand.Parameters.Add(new SqlParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SqlParameter("@FileName", FileNameExt)); // insertCommand.ExecuteNonQuery(); } } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); } } } }

    Read the article

< Previous Page | 4 5 6 7 8 9  | Next Page >