Show a message-box when the database is empty - c#

thanks for viewing my question. Basically, when the user clicks on a button, it will either say one of the following in a message box based on what the database has: Your holiday has been authorised, your holiday has been declined or your holiday request has been sent.
I want it so that when the user clicks on the button and there isn't any data in the database because the user hasn't sent a holiday request, to receive a message box saying that they haven't booked an holiday.
Here's my code:
private void button2_Click_1(object sender, EventArgs e)
{
System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["Login"];
SundownDatabaseEntities6 db = new SundownDatabaseEntities6();
int id = Convert.ToInt32(((Login)f).idTb.Text);
var getrecords = db.Holidays.Where(a => a.Id == id).ToList();
foreach (var record in getrecords)
{
if (record.YesOrNo == "yes")
{
MessageBox.Show("The manager has accepted your holiday (From " + record.Datefrom + " - " + record.Dateto + ").");
}
else if (record.YesOrNo == "no")
{
MessageBox.Show("The manager has declined your holiday request (" + record.Datefrom + " - " + record.Dateto + ").");
}
else if (record.YesOrNo == null)
{
MessageBox.Show("Your holiday request (" + record.Datefrom + " - " + record.Dateto + ") has been sent.\nWaiting for manager to authorise it...");
}
else if (record != null)
{
MessageBox.Show("You have not booked an holiday.");
}
}
}
Problem is on the last bit of the code, the 'else if(record != null)' doesn't check if the database is empty. Any suggestions? Thanks!

You should check getrecords.Count()
var getrecords = db.Holidays.Where(a => a.Id == id).ToList();
if (getrecords.Count() == 0)
{
// ... here your logic
}
Or
if (!db.Holidays.Any ())
Because it won't go to foreach if getrecords is empty.

Related

Extract only the values from SharePoint list with C#

I'm trying to extract the values of a SharePoint list to use with Revit to update the status parameters of some elements and after many tries I can connect and get the values if I know the keys for the dictionary inside every ListItem, but there are many problems with this approach.
The first one is the need to know the keys, sometimes the key is changed because of encoding, It would be more productive for me to get all the list values at one time. I tried to use a GetDataTable like some tutorials, but it appears that this don't work with the client.
The second is sometimes I can't get the value of the List but a description of the value, like "Microsoft.SharePoint.Client.FieldLookupValue".
Can someone help me with this issue? Bellow is the code I'm using.
using Microsoft.SharePoint.Client;
using System;
using System.Security;
namespace ConsoleTESTES
{
class Program
{
static void Main(string[] args)
{
string username = "USERNAME";
string siteURL = "SITEURL";
SecureString password = GetPassword();
GetAllWebProperties(siteURL, username, password);
}
public static void GetAllWebProperties(string siteURL, string username, SecureString password)
{
using (var context = new ClientContext(siteURL))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
// Assume the web has a list named "Announcements".
//List lista = context.Web.Lists.GetByTitle("Lista teste");
List lista = context.Web.Lists.GetByTitle("LIST");
// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"
// so that it grabs all list items, regardless of the folder they are in.
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = lista.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
context.Load(items);
context.ExecuteQuery();
//GET VALUES FROM LISTITEM
foreach (ListItem listItem in items)
{
Console.WriteLine(listItem["Setor"] + " " + "|" + " "
+ listItem["LocalServico"] + " " + "|" + " "
+ listItem["Equipe"] + " " + "|" + " "
+ listItem["Confeccao"]);
}
Console.ReadLine();
}
}
public static SecureString GetPassword()
{
ConsoleKeyInfo info;
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey();
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
}
You could get the values from the fields collection, but be warned that some special types of fields might require special treatment for the values and that you might not need to get all the values from the server (you can probably reduce your payload):
var items = lista.GetItems(query);
var fields = list.Fields;
var fieldsToIgnore = new[] { "ContentType", "Attachments" };
context.Load(items);
context.Load(fields);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
foreach (Field field in fields)
{
if (!fieldsToIgnore.Contains(fld.InternalName))
Console.WriteLine(item[field.InternalName]);
}
}
There are some fields that might not be loaded by default of that you might not need, so I have included the fieldsToIgnore to make your test easier.
After some search I found this solution to my FieldLookUpTable, to avoid errors if the item is null I added a if statement, but I could access the value with (listItem["Setor"] as FieldLookupValue).LookupValue. Here my messy code to check if is a LookupValue and get the value. Now I need to implement Pedro's solution to get all the values without the need to write everyone.
String setor = "";
String localServico = "";
String confeccao = "";
if (listItem["Setor"] != null && listItem["Setor"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = (listItem["Setor"] as FieldLookupValue).LookupValue;
}
else if (listItem["Setor"] != null && listItem["Setor"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = listItem["Setor"].ToString();
}
if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = (listItem["LocalServico"] as FieldLookupValue).LookupValue;
}
else if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = listItem["LocalServico"].ToString();
}
if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = (listItem["Confeccao"] as FieldLookupValue).LookupValue;
}
else if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = listItem["Confeccao"].ToString();
}
Console.WriteLine(setor + " " + "|" + " "
+ localServico + " " + "|" + " "
+ confeccao);

How do i store multiple data in the same text box from the database? c#

Hi thanks for viewing my question! I'm having a little trouble getting multiple data from my database. I'm trying to show multiple data in a single text box and it will not let me, of course.
My code:
string authorised = "notReviewed";
SundownDatabaseEntities5 dbb = new SundownDatabaseEntities5();
System.Windows.Forms.Form ff = System.Windows.Forms.Application.OpenForms["Login"];
int idd = Convert.ToInt32(((Login)ff).idTb.Text);
var getrecordd = dbb.Holidays.Where(a => a.Id == idd).SingleOrDefault();
if (getrecordd.Authorised == authorised)
{
holidaysAuthorisedTb.Text = "Your holiday request (" + getrecordd.Datefrom + " - "+getrecordd.Dateto+") has been sent. Waiting for manager to authorise it...";
}
FirstOrDefault(); gets the first data it finds but I need them all. How would I go about making it so that it will show multiple data instead of one? Thanks guys!
e.g. Text box:
Your holiday request (" + getrecordd.Datefrom + " - "+getrecordd.Dateto+") has been sent. Waiting for manager to authorise it...
Your holiday request (" + getrecordd.Datefrom + " - "+getrecordd.Dateto+") has been authorised.
You can get all records and then use foreach.
var getrecordds = dbb.Holidays.Where(a => a.Id == idd).ToList();
foreach (var getrecordd in getrecordds)
{
if (getrecordd.Authorised == authorised)
{
holidaysAuthorisedTb.Text += "Your holiday request (" + getrecordd.Datefrom + " - "+getrecordd.Dateto+") has been sent. Waiting for manager to authorise it...";
}
else
{
holidaysAuthorisedTb.Text += "Your holiday request (" + getrecordd.Datefrom + " - "+getrecordd.Dateto+") has been sent. Waiting for manager to authorise it..."
}
}
Or use ForEach method
dbb.Holidays.Where(a => a.Id == idd).ForEach ( x =>
{
if (x.Authorised == authorised)
{
holidaysAuthorisedTb.Text += "Your holiday request (" + x.Datefrom + " - "+x.Dateto+") has been sent. Waiting for manager to authorise it...";
}
else
{
holidaysAuthorisedTb.Text += "Your holiday request (" + x.Datefrom + " - "+x.Dateto+") has been sent. Waiting for manager to authorise it..."
}
});

Search data gridview using textbox and checkboxlist asp.net c#

I want to use textbox and checkboxlist to search data in gridview using asp.net c#. Using textbox can search the data. But for checkboxlist only can search the data when check only one checkbox. If check more than one checkbox, can't search the data. thanks a lot for helping.
the code:
c# code
protected void btnSearch_Click(object sender, EventArgs e)
{
if (cblDay.SelectedIndex != -1)
{
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
RptRateData.Day += val.Value + "";
}
}
}
RptRateData.RateAmount = txtRate.Text.Trim();
BindGrid();
}
code for class:
public string RateAmount { get; set; }
public string Day { get; set; }
internal DataSet GetRptRateSet()
{
DataSet tmpDS = new DataSet();
try
{
string strSQL = #"SELECT ComplexRateInfo.ComplexRateId,
ComplexRateDetailInfo.Day,
ComplexRateInfo.RateAmount
FROM ComplexRateInfo
LEFT JOIN ComplexRateDetailInfo ON ComplexRateInfo.ComplexRateId = ComplexRateDetailInfo.ComplexRateId ";
string whereSQL = " WHERE";
string orderBySQL = " order by Day ;";
int filterCount = 0; //to keep track of needed filter that are going to be used by the sql string
string[] sIndex = new string[2]; //to keep track of scalar variable needed by the sql, four string of sIndex because maximum filter available is 4
int indexCount = 0; //count to access sIndex members
//filter with or without day
if (_ds.Day != null && _ds.Day != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.Day;
indexCount++;
}
//filter with or without rate amount
if (_ds.RateAmount != null && _ds.RateAmount != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.RateAmount;
indexCount++;
}
//build complete query with no filter at all
if (filterCount == 0)
{
strSQL = strSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL));
}
//build complete query with 1 or more filter
else
{
strSQL = strSQL + whereSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL, sIndex));
}
}
catch (Exception ex)
{
throw ex;
}
return tmpDS;
}
There are two mistakes in your code.
Assigning values to RptRateData.Day from CheckBoxList.
Description: You assign selected values to object without using any separator. So For example if you have selected 1, 2, 4 days then as per your code, value of RptRateData.Day will be 124. Instead of that, it should be separated with comma as shown below:
var selectedDays = string.Empty;
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
selectedDays += "'" + val.Value + "',";
}
}
RptRateData.Day = selectedDays.TrimEnd(new char[] { ',' });
Now come to the second point which is in your SQL query which you make dynamically.
Description: In this query in WHERE clause you use Like operator for ComplexRateDetailInfo.Day. This will not work anymore. Instead of that you should use IN operator.
Note: Are you sure that your Like operator is working with curly braces ('{' and '}') and without '%' symbol ?

Getting all latest tweets c# console application

How can i at least get 3200 latest tweets from a public timeline? this is what i have done currently but it only returns me latest 200 tweets.
void GetUserTimeLine(TwitterContext ctx) {
var statusTweets =
from tweet in twitterCtx.Status
where tweet.Type == StatusType.User &&
tweet.Count == 3200 &&
tweet.ScreenName == "abc"
select tweet;
//PrintTweetsResults(statusTweets);
foreach (var tweet in statusTweets)
{
Console.WriteLine(
"(" + tweet.StatusID + ")" +
"[" + tweet.User.ID + "]" +
tweet.User.Name + ", " +
tweet.Text + ", " +
tweet.CreatedAt);
}
// DEFINE FILE PATH NAME
string dwnloadFilePath = #"C:\temp\Tweet.log";
// CREATE AN EMPTY TEXT FILE
FileStream fs1 = null;
if (!File.Exists(dwnloadFilePath))
{
using (fs1 = File.Create(dwnloadFilePath)) ;
}
// WRITE DATA INTO TEXT FILE
if (File.Exists(dwnloadFilePath))
{
using (StreamWriter sw = new StreamWriter(dwnloadFilePath))
{
statusTweets.ToList().ForEach(
tweet => sw.Write(
"{3}, Tweet ID: {2}, Tweet: {1}\n",
tweet.User.Name, tweet.Text, tweet.StatusID, tweet.CreatedAt));
}
}
Console.ReadLine();
}
Can someone please enlighten me?
Thanks,
10e5x
While you can fetch any of the last 3200 tweets in the time line, you can only fetch them in batches of 200 (see the twitter api for more details.)
You need to requery once you have processed the first 200 entries specifying the max id value as well as the count, where the max id is the lowest id from the set of tweets you have already processed.

Postback not working on mouse click in Safari

So I have a dropdown context box, which I use to select which item I am going to be working with.
Now everything seems to be working on all browsers except Safari. I have a type function that works fine in safari if you focus on the box and type the name in and hit enter. However my issue is with the mouse click. If I select an item from the dropdown and click it, the postback doesn't work until I hit enter on the keyboard.
Here is my .ascx.cs file
...
if (cboContext.Visible)
{
string postBackFunction = "function contextPostback() {\n"
+ "var newValue = document.getElementById(\"" + cboContext.ClientID + "\").value;\n"
+ "if (newValue != " + cboContext.SelectedValue + ") " + Page.ClientScript.GetPostBackEventReference(cboContext, "") + ";\n}";
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "contextPostback", postBackFunction, true);
if (Request.UserAgent.ToLower().IndexOf("chrome") > -1)
{
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
else if (Request.UserAgent.ToLower().IndexOf("safari") > -1)
{
cboContext.Attributes.Add("onclick", "contextPostback();");
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeyup", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
}
else
{
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
}
Here is the typeAhead() function
function typeAhead(e, nextFocus) {
//don't trap Ctrl+keys
if ((window.event && !window.event.ctrlKey) || (e && !e.ctrlKey)) {
// timer for current event
var now = new Date();
....
if (inputBuffer.accumString == "" || now - inputBuffer.last < inputBuffer.delay) {
//check for browsers
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
// make shortcut event object reference
var evt = e || window.event;
// get reference to the select element
var selectElem = evt.target || evt.srcElement;
// get typed character ASCII value
var charCode = evt.keyCode || evt.which;
// get the actual character, converted to uppercase
var newChar = "";
// get reference to the actual form selection list
// added cross browser fix to enable the context switcher to work properly
if (is_chrome) {
var selection = document.getElementById("ctl00_ContextSwitch1_cboContext").selectedIndex;
}
else {
var selection = document.getElementById(nextFocus);
}
....
Now I have a section in the typeAhead for the chrome browser, but everything I try for safari doesn't seem to allow me to use the mouse click to select an item.
Any help would be appreciated.
simple fix. safari recognizes onchange so once I added that, it worked fine.

Categories

Resources