I have some links on a page such as:
< a id="Digg" runat="server">< img alt="Digg" id="imgDigg" runat="server" src="~/resources/images/icons/social/digg_32.png" border="0" />< /a>
I have a database table that can "turn" them on or off, in my code behind I have the following:
string[] SocialMedia = new string[] { "Twitter", "Facebook", "LinkedIn", "Digg", "Email", "Print" };
private void CheckForSocialMedia()
{
int i = 0;
for (i = 0; i < SocialMedia.Length; i++)
{
bool AddSocialMedia = (bool)AllowSocialMedia(SocialMedia[i]);
if (AddSocialMedia == false)
{
// Hide the link: Digg.Visible = false;
}
}
}
protected bool AllowSocialMedia(string sSocialMedia)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString);
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = " select Settings.AllowsocialMedia " +
" from ArticleSocialMediaSettings Settings " +
" inner join SocialMedia on Settings.SocialMediaId = SocialMedia.id " +
" where SocialMedia.NetworkName = '" + sSocialMedia + "'" +
" and Settings.RetailerId = '1234'";
myConnection.Open();
try
{
SqlDataReader myReader = myCommand.ExecuteReader();
if (myReader.Read())
{
return (bool)myReader["AllowsocialMedia"];
}
}
catch (Exception ex)
{
throw ex;
}
return true;
}
How can I hide the link if the function returns false? Or is there a better way to do this?
It looks like that is the correct method for checking the database. To hide the link you can use:
document.getElementById("Digg").style.display = "none";
right where your comment is.
Redesigned it using a datalist
Related
Im trying to update rows in my table using loop, I get no error but nothing changed in my data...Thats my code.. What am I missing ?
private void updateZipInDB(List<ZipObj> zipCodeToUpdate)
{
var comm = "";
string DbConnString = ConfigurationManager.AppSettings["dbConnectionString"].ToString();
using (SqlConnection conn = new SqlConnection(DbConnString))
{
comm = "UPDATE Account SET address1_postalcode = #newVal WHERE AccountId = #accountID";
using (SqlCommand command = new SqlCommand(comm, conn))
{
conn.Open();
command.Parameters.AddWithValue("#newVal", "f");
command.Parameters.AddWithValue("#accountID", "f");
for (int i = 0; i < zipCodeToUpdate.Count; i++)
{
zipCodeToUpdate[i].NewVal + "' WHERE AccountId = '" + zipCodeToUpdate[i].AccountId + "'";
command.Parameters["#newVal"].Value = zipCodeToUpdate[i].NewVal;
command.Parameters["#accountID"].Value = zipCodeToUpdate[i].AccountId;
command.ExecuteNonQuery();
}
conn.Close();
}
}
}
I constantly write an error, the database is locked. I just can not understand why this is happening.
db_login.cs
private db_controller _dbctrl = new db_controller();
public SqliteDataReader dataread;
private string query;
//this two inputField,
public void LoginToGo()
{
login = _login.captionText.text;
pass = _pass.text.ToString();
query = "SELECT id from users where users = '" + login + "' AND pass = '" + pass + "'";
try
{
dataread = _dbctrl.ExecuteReader(query);
if(dataread.HasRows & dataread != null)
{
while (dataread.Read())
{
VerifyAdmin();
_dbctrl.Disconnect();
}
}
else
{
errortxt.text = "Неверный логин или пароль, пожалуйста повторите!";
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void VerifyAdmin() //Who are you, admin or user
{
login = _login.captionText.text;
query_access = "SELECT root from users where users = '" + login + "'";
try
{
dataread = _dbctrl.ExecuteReader(query_access);
while (dataread.Read())
{
if(dataread[0].ToString() == "0" || dataread[0].ToString() == null)
{
MainMenu();
}
else
{
AdminMenu();
}
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void AdminMenu()
{
JOIN.SetActive(false);
ADMIN.SetActive(true);
}
public void MainMenu()
{
JOIN.SetActive(false);
MAIN.SetActive(true);
}
db_controller.cs
public SqliteConnection con_db;
public SqliteCommand cmd_db;
public SqliteDataReader rdr_db;
public void connections()
{
try
{
if(Application.platform != RuntimePlatform.Android)
{
path = Application.dataPath + "/StreamingAssets/db.bytes"; // Путь для Windows
}
else
{
path = Application.persistentDataPath + "/db.bytes"; // Путь для Android
if(!File.Exists(path))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "db.bytes");
while (!load.isDone) { }
File.WriteAllBytes(path, load.bytes);
}
}
con_db = new SqliteConnection("URI=file:" + path);
con_db.Open();
if (con_db.State == ConnectionState.Open)
{
debugText.text = path.ToString() + " - is connected";
Debug.Log(path.ToString());
}
}
catch (Exception ex)
{
debugText.text = ex.ToString();
}
}
//Тут я создаю метод отключения
public void Disconnect()
{
con_db.Close();
}
public SqliteDataReader ExecuteReader(string query)
{
connections();
try
{
cmd_db = new SqliteCommand(query, con_db);
rdr_db = cmd_db.ExecuteReader();
return rdr_db;
}
catch (Exception ex) { debugText.text = ex.ToString(); return null; }
}
//Тут я записываю данные. Заодно решил проверить закрыто ли соединение.
public void SetDB()
{
if (con_db.State == ConnectionState.Open)
{
Debug.Log("open");
}
else
{
Debug.Log("close!");
}
//The connection is closed. But I can not complete the request cmd_db.ExecuteNonQuery();
connections();
try
{
brand = AutoName.captionText.text;
model = AutoModel.captionText.text;
years = OldAuto.captionText.text;
number = GosNumber.text.ToString();
nusers = UserName.text.ToString();
dbirthday = DBirthday.captionText.text;
mbirthday = MBirthday.captionText.text;
ybirthday = YBirthday.captionText.text;
mobile = Mobile.text.ToString();
cmd_db = new SqliteCommand("INSERT INTO clients(brand,model,years,number,nusers,dbirthday,mbirthday,ybirthday,mobile,groupmodel) values('" + brand + "', '" + model + "','" + years + "','" + number + "','" + nusers + "','" + dbirthday + "','" + mbirthday + "','" + ybirthday + "','" + mobile + "','" +groupmodel+ "')" , con_db);
cmd_db.ExecuteNonQuery(); //Swears, says that the base is locked. And why? I just read the data and the connection was closed.
}
catch (Exception ex) { debugText.text = ex.ToString(); }
Disconnect();
}
the documentation says:
This error code occurs when you try to do two incompatible things with the database at the same time from the same connection to the database.
But the connection with the base is closed.
Maybe I'm missing something, or not doing the right thing. I ask for help to clarify this issue.
i have a service that returns a json string: {"IsExisting": "true"} if the user is verified in the database. however if i put the correct credentials the code enters the null condition for response instead of the true condition. what could be the problem?
here's my controller.js code:
$scope.enterlogin = function(usern,pass)
{
console.log('username is = ' + usern);
loginService.getUser(usern,pass).then(function(response){
console.log('user is = ' + response);
var obj = JSON.parse(response);
console.log('object is ' + obj['IsExisting'] );
if(obj['IsExisiting'] == null)
{
alert('Account does not exist. Please check your credentials.');
}
else
{
if(localStorage['firstTimeLoad']!='TRUE')
{
$scope.hide();
localStorage['firstTimeLoad']='TRUE';
$state.go('helpExtra');
}
else
{
$scope.hide();
$state.go('menu.mainMenu');
}
}
});
}
here's my service code:
//angularSoap Login
.factory('loginService', ['$soap', function($soap){
var base_url = "http://localhost/UserService3/WebService1.asmx";
return {
getUser: function(usern,pass){
console.log('code side usern is = ' + usern + "" + pass);
return $soap.post(base_url, "getUserbyUsername", { uname: usern, passw: pass});
}
}
}])
and here's my webservice code:
[WebMethod]
public string getUserbyUsername(string uname, string passw)
{
string cs = "Data Source =.; Initial Catalog = UsersDB; Integrated Security = True";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetUserByUsername", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter(#"Username", uname);
SqlParameter parameter2 = new SqlParameter(#"Password", passw);
cmd.Parameters.Add(parameter);
cmd.Parameters.Add(parameter2);
User user = new User();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// user.Username = reader["Username"].ToString();
// user.Password = reader["Password"].ToString();
user.IsExisting = reader["IsExisting"].ToString();
}
con.Close();
return new JavaScriptSerializer().Serialize(user);
}
}
The problem is with the spellings of the property you are trying to access on your object.
It should be
if(obj['IsExisting'] == null)
{
alert('Account does not exist. Please check your credentials.');
}
and not
if(obj['IsExisiting'] == null)
I'm having issue with creating product code in recursion.
What I want to do is:
I enter code 1000
-If code exist in database regenerateCode(string code)
-else insert into database
Code:
(...)
if(codeExist)
CodeTB.Text = regenerateCode(string toParse); //toParse = 1000
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
// if code still exist in database, regenerate it
regenerateCode(helper);
}
else
{
//else return code
return helper;
}
}
}
}
return helper;
}
Actually it works fine with example:
1000 (exist)
1001 (exist)
1002 (not exist, insert), but
when code = 1002, it goes into line with else {return helper;} and have no idea why going again to regenerateCode() method..
Any ideas?
It happens because you do nothing with the return value. You pass helper to the recursion, but do not place the return value anywhere. your method should look like this:
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// Return the next code that doesn't exist
return rdr.HasRows ? regenerateCode(helper) : helper;
}
}
}
}
Also, remember that while string are reference types, they are immutable. which means that a string that is passed as an argument would not change like a normal array. see: How are strings passed in .NET?
I am following a tutorial "Export data from sql server database to excel in wpf". Now I can achieve the function successfully. But in the exported Excel file, there is no column names (database column headers like CustomerId, CustomerName, city, postcode, telephoneNo...)
.
How can I get this feature? Also, how can I open a SaveAs dialogue? Thanks. The following is my code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=Client;Integrated Security=SSPI;";
cnn.Open();
sql = "select * from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
I'm not an expert in this, but I believe that you can use an underscore character (_) in a Range object to select or edit a column header:
xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";