How To Get SqlConnection Instantiated? - c#

I am following a tutorial to make an ASP.NET web app and came to the part of establishing a connection to my SQL database item I added withing VisualStudio via Add>New Item command when right-clicking on my project name in Solution Explorer.
However, after putting the appropriate namespaces, VS is not recognizing the SQLConnection I'm trying to instantiate.
I keep getting the error: "the modifier 'new' is not valid for this item" among others.
I already tried removing the "#" symbol, already tried putting the path in a string, but now VS is not even recognizing a simple string instantiation!
Here is code version 1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace AdressBook
{
public partial class WebForm1 : System.Web.UI.Page
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True");
Here is code version 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace AdressBook
{
public partial class WebForm1 : System.Web.UI.Page
string datapath = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True"
SqlConnection conn = new SqlConnection(datapath);
I expect there to be no red/green underlines and be able to connect to my database when a button is clicked. What is wrong?

Maybe this is a copy/paste error, but you're missing the curly brace at the start of the class:
namespace AdressBook
{
public partial class WebForm1 : System.Web.UI.Page
{ //<---- opening curly brace required!
string datapath = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True"

I have tried the following and it works for my VS2017.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\MySelf\\Documents\\Visual Studio 2017\\Projects\\TestSQL\\TestSQL\\App_Data\\Database.mdf;");
}
}

Related

Can't Complete Code over File error how do i fix

I can't seem to figure out what is going on here.
I have posted below my code and a photo:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace test
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
ChromeOptions options = new ChromeOptions();
options.AddExtensions(new File("pathtoextentions.crx"));
IWebDriver driver = new ChromeDriver(options);
//Test Opening Website
driver.Navigate().GoToUrl("https://google.com");
}
}
}
I have also uploaded a photo here where it show my error is on new File: https://ibb.co/Lk72dsD
Error CS0712 Cannot create an instance of the static class 'File'
What am I doing wrong?
File is a static class, you can't create instances of it like new File().
Looking at ChormeOptions.AddExtensions, it accepts an array or an IEnumerable of string.
So, we could use an array in your case. To do so, replace this:
options.AddExtensions(new File("pathtoextentions.crx"));
with this:
options.AddExtensions(new[] { "pathtoextentions.crx" });

AudioVideoPlayback doesn`t work at all. How to fix it?

I am new to C# and testing Microsoft.DirectX.AudioVideoPlayback library function.(using VS2019)
VS said there are no error, but nothing happened when I compiled it.
I have tested below code line by line. and found that Init() function does not work at all. I have tested other paths such as
#"C:\Users\name\Videos\sample.mp4"
"C:\Users\name\Videos\sample.mp4"
"C:\Users\name\Videos\sample.mp4"
but all of them does not work at all too.
How to fix the code and why it did`t work properly?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.DirectX.AudioVideoPlayback;
using System.IO;
namespace hello
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Init();
}
public void Init()
{
Video v = Video.FromFile(#"C:\Users\name\Videos\sample.mp4");
v.Owner = this;
v.Size = new Size(1920, 1080);
v.Play();
}
}
}
This might be too simple question, but cannot gain any solution from other answers in this site.

ApplicationContext.Current is coming null

I found same question in stack over flow as here and tried same think but still I am receiving ApplicationContext.Current as null.
I am making the web service where I need to pull out a couple of pieces of data from an Umbraco database. I don't need any of the Umbraco views or any of that stuff. I'm new to the Umbraco Core libraries.
What I did was get a below reference to my new web service project
umbraco.dll
Umbraco.Core.dll
umbraco.DataLayer.dll
umbraco.editorControls.dll
umbraco.MacroEngines.dll
umbraco.providers.dll
Umbraco.Web.UI.dll
umbraco.XmlSerializers.dll
UmbracoExamine.dll
And the below class code where I am receiving ApplicationContext.Current as null
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Web.Mvc;
using umbraco.MacroEngines;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using umbraco.NodeFactory;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using umbraco.cms.businesslogic.media;
using umbraco.BusinessLogic;
using System.Configuration;
using log4net;
using System.Reflection;
using Umbraco.Core.Logging;
using System.Web.Optimization;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI.WebControls;
using Stripe;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Security;
using Newtonsoft.Json;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.IO;
public class RegisterUserController : UmbracoApiController
{
public static string UmbracoConnectionString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;
public static IMemberService memberService = ApplicationContext.Current.Services.MemberService;// Here I am getting ApplicationContext.Current as null
}
But I am calling this class I am getting ApplicationContext.Current as null.
So because of that I have Many methods in this class which works on memberService and due to this null reference they are not working. Even other methods which are not using member service are not being called.
For me, the code below seems to work.
public class TestApiController : UmbracoApiController
{
private static string _umbracoConnectionString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;
private static IMemberService _memberService = global::Umbraco.Core.ApplicationContext.Current.Services.MemberService;
public int GetTest()
{
var memberCount = _memberService.Count();
return memberCount;
}
}
If the above code isn't working for you e.g. with AJAX, try the below code:
public class TestApiController : UmbracoApiController
{
public int GetTest()
{
var ms = Services.MemberService;
return ms.Count();
}
}

The type or namespace name 'SQLite' does not exist in the namespace 'System.Data'

I am new with C#. I am using Visual Studio 13, my problem is that it's throwing me this error:
The type or namespace name 'SQLite' does not exist in the namespace 'System.Data' (are you missing an assembly reference?)
Yes, I added references from here https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
and I followed the tutorial from here :
https://www.youtube.com/watch?v=N0hL5sGkUSA
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace PercobaanDulu
{
public partial class Form1 : Form
{
string connString;
public Form1()
{
InitializeComponent();
connString = #" Data Source = C:\Users\Febry Fairuz\Desktop\dbDemoLagi.db; Version = 3";
}
private void btnConnect_Click(object sender, EventArgs e)
{
using (SQLiteConnection con = new SQLiteConnection(connString)) {
try {
con.Open();
if(con.State == ConnectionState.Open){
MessageBox.Show("Koneksi berhasil dengan SQLite");
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
}
}
Can you help me ?
I think the problem is that you are referencing incorrect version of System.Data.Sqlite.dll which is not compatible with version of .NET which you are using. You should check and install the compatible version of the dll to get rid of your problem.
If you are using the .Net 4.5 then you can try the NuGet package System.Data.SQLite.
A direct link for the package is here

Get Session variable inside a method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Web.Security;
using System.Data;
using System.IO;
using SurelyKnown.Core;
using System.Configuration;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Xml;
using System.Windows.Forms;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
int newOrgID = Convert.ToInt32(Session["uOrgID"].ToString());
The error is on the last line
CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'
WHat should I do to get the session value inside the method.
Use HttpContext.Current.Session
int newOrgID=0;
if(HttpContext.Current.Session["uOrgID"]!=null)
{
int.TryParse(HttpContext.Current.Session["uOrgID"].ToString(),out newOrgID);
}
check for null before using it, something like this:
if(Session["uOrgID"] != null)
{
int newOrgID = Convert.ToInt32(Session["uOrgID"].ToString());
}
You should also read this article to really understand how to access Session state from web services (including web and page methods): Using ASP.NET Session State in a Web Service

Categories