I working on a web application using SQL server express 2014. In there I'm used to set some data to a table.there's no errors occurring but data doesn't set to the table.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<connectionStrings>
<add name="connect" connectionString="Data Source=LAKSHITHA\SQLEXPRESS;Initial Catalog=EMS1;Integrated Security =True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>
here is my aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication2
{
public partial class Reg2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
// con.ConnectionString = "Data Source=LAKSHITHA/SQLEXPRESS ;Initial Catalog=EMS1;Integrated Security=true";
con.Open();
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Epersonal " + " (Emp_Id,NIC,Gender,B_day,Nationality,Marital_status,Work_Role)values(#Emp_Id,#NIC,#Gender,#B_day,#Nationality,#Marital_status,#Work_Role)", con);
cmd.Parameters.AddWithValue("#Emp_Id", TextBox1.Text);
cmd.Parameters.AddWithValue("#NIC", nic.Text);
cmd.Parameters.AddWithValue("#Gender", DropDownList2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#B_day", bday.Text);
cmd.Parameters.AddWithValue("#Nationality", ntionl.Text);
cmd.Parameters.AddWithValue("#Marital_status", DropDownList3.SelectedItem.Value);
cmd.Parameters.AddWithValue(" #Work_Role", DropDownList1.SelectedItem.Value);
Response.Write("cannection made");
Response.Redirect("log.aspx");
// con.Open();
con.Close();
//cmd.ExecuteNonQuery();
}
}
}
[here is my table and tz attributes]
after setting the data there is no data in the database. In my logging form I have connected the DB and in there I'm using a DB data and logging to the application
Can you please tell whats wrong in here>???
You are not executing the command. Also, wrap SqlCommand ad SqlConnection in using clauses.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ToString())
{
using (SqlCommand cmd = new SqlCommand("insert into Epersonal (Emp_Id,NIC,Gender,B_day,Nationality,Marital_status,Work_Role)values(#Emp_Id,#NIC,#Gender,#B_day,#Nationality,#Marital_status,#Work_Role)", con))
{
cmd.Parameters.AddWithValue("#Emp_Id", TextBox1.Text);
cmd.Parameters.AddWithValue("#NIC", nic.Text);
cmd.Parameters.AddWithValue("#Gender", DropDownList2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#B_day", bday.Text);
cmd.Parameters.AddWithValue("#Nationality", ntionl.Text);
cmd.Parameters.AddWithValue("#Marital_status", DropDownList3.SelectedItem.Value);
cmd.Parameters.AddWithValue(" #Work_Role", DropDownList1.SelectedItem.Value);
con.Open();
Response.Write("cannection made");
cmd.ExecuteNonQuery();
}
}
Response.Redirect("log.aspx");
EDIT:
Is better to use Add instead of AddWithValue, to avoid errors when infering the correct Database type.
For example:
cmd.Parameters.Add("#Nationality", SqlDbType.Varchar, 20).Value = ntion1.Text; //Picked a random size of 20, use your specified size instead
Use it with all of your values.
Related
I am tried to add some data into the database but it not adding inside the database table ,But it didnt show any exception also.I dont know whats the problem
try
{
SqlConnection con = new SqlConnection(#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue','10')", con);
cmd.ExecuteNonQuery();
con.Close();
}
My App Config file
[![<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="StoreContext" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>
</configuration>][1]][1]
My Table
CREATE TABLE [dbo].[Store] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] VARCHAR (20) NOT NULL,
[Description] VARCHAR (100) NULL,
[Expences] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
You have an error in your request, Expences is a integer :
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue',10)", con);
Try below code, below code is written without using any tool so please try to adjust the code.
try
{
DbContext xyz = new DbContext();
Store oStore = new Store();
oStore.Item = "pen";
oStore.Description = "blue";
oStore.Expences = 10;
xyz.Stores.Add(oStore);
xyz.SaveChanges(); // never forgot to do SaveChanges
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I'm at wits end. I'm trying to load up a ReportViewer with both valid aspx code and ReportViewerForMVC code wind up here. First, the error spread:
Uncaught SyntaxError: Unexpected token < WebResource.axd:1
Uncaught SyntaxError: Unexpected token < GetSysWideQuizReport:67
Uncaught ReferenceError: ReportViewerForMvc is not defined(anonymous
function) # GetSysWideQuizReport:67 Uncaught SyntaxError: Unexpected
token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ReportViewerWebForm.aspx:40
Uncaught Error: ASP.NET Ajax client-side framework failed to
load.(anonymous function) # ReportViewerWebForm.aspx:40
ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token <
Reserved.ReportViewerWebControl.axd:1
Uncaught SyntaxError: Unexpected token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ReportViewerWebForm.aspx:51
Uncaught ReferenceError: Sys is not defined(anonymous function) #
ReportViewerWebForm.aspx:51 ReportViewerWebForm.aspx:114
Uncaught ReferenceError: Sys is not defined ReportViewerWebForm.aspx:114
The View:
#using ReportViewerForMvc;
#using Microsoft.Reporting.WebForms;
#using App.Models;
<style>
iframe{
width:900px;
}
</style>
#{
ViewBag.Title = "LocalReportExample";
}
<h2>Local report example</h2>
#Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)
Controller:
public ActionResult GetSysWideQuizReport([Bind(Include = "Topic, Date1, Date2")] QuizReporting quizParams)
{
ReportViewer reportViewer = new ReportViewer();
reportViewer.ProcessingMode = ProcessingMode.Local;
reportViewer.SizeToReportContent = true;
reportViewer.Width = Unit.Percentage(100);
reportViewer.Height = Unit.Percentage(100);
reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + #"/ReportViews/System Quiz Report.rdlc";
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", QuizData(quizParams)));
ViewBag.ReportViewer = reportViewer;
return View();
}
private DataTable QuizData(QuizReporting quizParams)
{
DataSet ds = new DataSet("DataSet1");
using(SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = GetConnectionString();
SqlCommand cmd = new SqlCommand("SystemQuizReport", connection);
cmd.Parameters.AddWithValue("#TopicID", quizParams.Topic.TopicID);
cmd.Parameters.AddWithValue("#Date1", "2015/04/13");
cmd.Parameters.AddWithValue("#Date2", "2015/04/16");
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
return ds.Tables[0];
}
}
static private string GetConnectionString()
{
return "Data Source=(localdb)\\v11.0; Initial Catalog=LocalDb-20140822124213; Integrated Security=True;";
}
An excerpt of web.config:
<system.web>
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" />
</httpHandlers>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5">
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</buildProviders>
</compilation>
<httpRuntime targetFramework="4.5" />
<!--<hostingEnvironment shadowCopyBinAssemblies="false" /> -->
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</handlers>
</system.webServer>
I've done the following to fix it:
Made sure all Nuget packages/frameworks are up to date
Examined the console output in Chrome. It looks like the AXD files are trying to render the base home page of my application, and I don't know why.
Disabled all authorization requirements in FilterConfig and this has not worked.
I'm pulling my hair out so much with this so I hope you can help me out!
When I try to use a Session veriable in InitializeCulture, I get the folowing error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
This is the code where the error is thrown
public class BasePage : Page
{
public string Lang { get; set; }
protected override void InitializeCulture()
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["lang"]))
{
Session["lang"] = Request.QueryString["lang"].ToLower();
}
if (Session["lang"] != null && !string.IsNullOrEmpty((string)Session["lang"]))
{
Lang = (string)Session["lang"];
string selectedCulture = Lang == "nl" ? "nl-BE" : "fr-BE";
UICulture = selectedCulture;
Culture = selectedCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture);
}
base.InitializeCulture();
}
}
}
I changed my Web.Config, as sugested in the error. But It keeps throwing the same error.
<pages enableSessionState="true">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpModules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionStateModule" />
<add type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" name="UrlRewriter"/>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Does anyone has a solution? Thanks!!!
Try to set enableSessionState=true in the pages section.
<system.web>
<pages enableSessionState="true">
</system.web>
Also, if you're using IIS7 on Windows 2008, your modules should be inside the <system.webServer> section, instead of <system.web>.
I have the following module
public class LowerCaseRequest : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(this.OnBeginRequest);
}
public void Dispose() { }
public void OnBeginRequest(Object s, EventArgs e) {
HttpApplication app = (HttpApplication)s;
if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) {
if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower();
response.SuppressContent = true;
response.End();
}
if (!app.Context.Request.Url.ToString().StartsWith(#"http://zeeprico.com")) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(#"http://zeeprico.com", #"http://www.zeeprico.com");
response.SuppressContent = true;
response.End();
}
}
}
}
the web.config looks like
<system.web>
<httpModules>
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<add name="LowerCaseRequest" type="LowerCaseRequest" />
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
It works grate on my PC running XP and IIS 5.1
but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out.
Thanks
On IIS7 and higher use
<configuration>
<system.webServer>
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
</system.webServer>
</configuration>
Above is correct for IIS 7.5
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
the only problem I got, is that instance of application pool for particular application should be set to managed Pipeline = Integrated, not Classic..
or:
Using Classic Mode
If your application is to use Classic mode, then make sure that your application is configured for that type of pool and your modules are configured in system.web section and not in system.webServer section of web.config file.
In IIS go to feature view select module
double click to module then right click and press (Add Managed Module)
then put name and type as defined in web.config
example:
<httpModules>
<add name="CustomModule" type="WebApplication.Security.CustomModule" />
</httpModules>
I'm trying to use the MySQLRoleProvider(MySql.Web, Version=6.2.2.0) with Visual Web Developer 2008.
When trying to add a role I get an exception "Table 'test.my_aspnet_applications' doesn't exist"
if (!Roles.RoleExists("TestRole"))
{
Roles.CreateRole("TestRole");
}
Can someone tell me where I went wrong. Or tell me how to generate / find the correct database script to create the role, membership, profile ... MySql tables.
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider"/>
<add autogenerateschema="true" connectionStringName="LocalMySqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</membership>
<profile enabled="true" defaultProvider="MySQLProfileProvider">
<providers>
<remove name="MySQLProfileProvider"/>
<add name="MySQLProfileProvider" autogenerateschema="true" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="true" defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider"/>
<add autogenerateschema="true" connectionStringName="LocalMySqlServer" applicationName="/" name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</roleManager>
Have you used the ASP.Net configuration tool to switch your application's provider to the MySQL provider? I believe this is what triggers the MySQL provider to automatically generate the schema.
Follow this codeproject howto and you'll be fine.
If your database won't generate try this:
Create a custom ContextInitializer and add this to the Global.asax:
Database.SetInitializer(new CreateMySqlDatabaseIfNotExists<MyContext>());
internal class CreateMySqlDatabaseIfNotExists<TContext>: IDatabaseInitializer<TContext> where TContext : MyContext
{
public void InitializeDatabase(TContext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(false))
throw new InvalidOperationException("The model has changed!");
}
else
{
CreateMySqlDatabase(context);
Seed(context);
}
}
private void CreateMySqlDatabase(TContext context)
{
try
{
context.Database.Create();
return;
}
catch (MySqlException ex)
{
// Ignore the parse exception
if (ex.Number != 1064)
{
throw;
}
}
// Manually create the metadata table
using (var connection = ((MySqlConnection) context
.Database.Connection).Clone())
using (var command = connection.CreateCommand())
{
command.CommandText =
#"
CREATE TABLE __MigrationHistory (
MigrationId mediumtext NOT NULL,
CreatedOn datetime NOT NULL,
Model mediumblob NOT NULL,
ProductVersion mediumtext NOT NULL);
ALTER TABLE __MigrationHistory
ADD PRIMARY KEY (MigrationId(255));
INSERT INTO __MigrationHistory (
MigrationId,
CreatedOn,
Model,
ProductVersion)
VALUES (
'InitialCreate',
#CreatedOn,
#Model,
#ProductVersion);
";
command.Parameters.AddWithValue(
"#Model",
GetModel(context));
command.Parameters.AddWithValue(
"#ProductVersion",
GetProductVersion());
command.Parameters.AddWithValue(
"#CreatedOn",
DateTime.Now);
connection.Open();
command.ExecuteNonQuery();
}
}
private byte[] GetModel(TContext context)
{
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(
memoryStream,
CompressionMode.Compress))
using (var xmlWriter = XmlWriter.Create(
gzipStream,
new XmlWriterSettings {Indent = true}))
{
EdmxWriter.WriteEdmx(context, xmlWriter);
}
return memoryStream.ToArray();
}
}
private string GetProductVersion()
{
return typeof (DbContext).Assembly
.GetCustomAttributes(false)
.OfType<AssemblyInformationalVersionAttribute>()
.Single()
.InformationalVersion;
}
protected void Seed(TContext context)
{ // ...
context.SaveChanges();
}
}