Filtering LINQ query - asp.net

I have problem that is bothering me last couple of days.
I need to filter LINQ query using comboboxes and textboxes. The problem is I can't manage to get the result and I always get the empty gridview (used for showing filtered data).
Can anyone help me why am I getting no results at all? I've checked the debugger and the data sent to query is valid, although, I'm not sure about "string.Empty" value.
Here is the code:
string naziv, nazivEn, adresa, tel, fax, mob, email, web, oib, tip, mjesto;
if (chkMjesto.Checked == true)
{
mjesto = cbMjesto.SelectedItem.Text;
}
else
{
mjesto = string.Empty;
}
if (chkTip.Checked == true)
{
tip = cbTip.SelectedItem.Text;
}
else
{
tip = string.Empty;
}
string tema;
if (chkTema.Checked == true)
{
tema = cbTema.SelectedItem.Text;
}
else
{
tema = string.Empty;
}
if (chkAdresa.Checked == true)
{
adresa = txtAdresa.Text;
}
else
{
adresa = string.Empty;
}
if (chkTelefon.Checked == true)
{
tel = txtTelefon.Text;
}
else
{
tel = string.Empty;
}
if (chkMobitel.Checked == true)
{
mob = txtMobitel.Text;
}
else
{
mob = string.Empty;
}
if (chkEmail.Checked == true)
{
email = txtEmail.Text;
}
else
{
email = string.Empty;
}
if (chkWeb.Checked == true)
{
web = txtWeb.Text;
}
else
{
web = string.Empty;
}
if (chkOIB.Checked == true)
{
oib = txtOIB.Text;
}
else
{
oib = string.Empty;
}
if (chkNaziv.Checked == true)
{
naziv = txtNaziv.Text;
}
else
{
naziv = string.Empty;
}
if (chkNazivEn.Checked == true)
{
nazivEn = txtNazivEn.Text;
}
else
{
nazivEn = string.Empty;
}
if (chkFax.Checked == true)
{
fax = txtFax.Text;
}
else
{
fax = string.Empty;
}
if (rblOrganizator.SelectedItem.Value == "Nije")
{
var pretraga = from t in db.tijeloes
where t.tijelo_naziv.Contains(naziv) && t.tijelo_adresa.Contains(adresa) && t.tip_tijela.tip_tijela_naziv.Contains(tip) && t.mjesto.mjesto_naziv.Contains(mjesto)
where t.tijelo_telefon.Contains(tel) && t.tijelo_fax.Contains(fax) && t.tijelo_email.Contains(email) && t.tijelo_mob.Contains(mob) && t.tijelo_web.Contains(web) && t.tijelo_oib.Contains(oib) && t.tijelo_naziv_en.Contains(nazivEn)
select new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv};
gvTijelo.DataSource = pretraga;
gvTijelo.DataBind();
if (pretraga.Count() != 0)
{
gvTijelo.HeaderRow.Cells[0].Text = "Naziv";
gvTijelo.HeaderRow.Cells[1].Text = "OIB";
gvTijelo.HeaderRow.Cells[2].Text = "Tip tijela";
gvTijelo.HeaderRow.Cells[3].Text = "Adresa";
gvTijelo.HeaderRow.Cells[4].Text = "Mjesto";
gvTijelo.HeaderRow.Cells[5].Text = "Regionalni centar";
}
}

The string.Empty seems to the culprit. I would bet the SQL being generated is checking if a field contains '', which just won't likely work with data in that field.
Your best bet is to start the query before your conditionals, then append a where to it if the corresponding check box is checked.
var pretraga = db.tijeloes;
if (chkMjesto.Checked == true)
{
pretraga = pretraga.Where(t => t.tijelo_naziv.Contains(cbMjesto.SelectedItem.Text));
}
if (chkTip.Checked == true)
{
pretraga = pretraga.Where(t => t.tip_tijela.tip_tijela_naziv.Contains(cbTip.SelectedItem.Text));
}
...
pretraga = pretraga.Select(t => new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv });
// Bind to pretraga.
...

If I were you I would declare all the variables at the top seperately like
string naziv = string.empty;
string whatever = string.empty; etc
Doing this will make your code smaller because you can get rid of the else statements as the variables are already set.
Sorry not a solution but might thin down the code for you a little :)

Related

How to apply different filter options for different columns in telerik radgrid?

For telerik Radgrid, we are getting default values for filtering columns. But I need to have different filtering options for different columns.
I am able to remove some of the options like this
protected void RadGrid1_Init(object sender, System.EventArgs e)
{
GridFilterMenu menu = RadGrid1.FilterMenu;
int i = 0;
while (i < menu.Items.Count)
{
if (menu.Items[i].Text == "NoFilter" || menu.Items[i].Text == "Contains" || menu.Items[i].Text == "EqualTo" || menu.Items[i].Text == "GreaterThan" || menu.Items[i].Text == "LessThan")
{
i++;
}
else
{
menu.Items.RemoveAt(i);
}
}
}
But the problem here is filter options are getting removed for all the columns. I need different filter options for different columns.
Server side options is preferred.
Thanks in advance
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/Filtering/reduce-the-filter-menu-options
Direct from Telerik: This is not possible using server-side code. You must use the client-side example from the link above (pasted below):
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
var column = null;
function MenuShowing(sender, args) {
if (column == null) return;
var menu = sender; var items = menu.get_items();
if (column.get_dataType() == "System.String") {
var i = 0;
while (i < items.get_count()) {
if (!(items.getItem(i).get_value() in { 'NoFilter': '', 'Contains': '', 'NotIsEmpty': '', 'IsEmpty': '', 'NotEqualTo': '', 'EqualTo': '' })) {
var item = items.getItem(i);
if (item != null)
item.set_visible(false);
}
else {
var item = items.getItem(i);
if (item != null)
item.set_visible(true);
} i++;
}
}
if (column.get_dataType() == "System.Int64") {
var j = 0; while (j < items.get_count()) {
if (!(items.getItem(j).get_value() in { 'NoFilter': '', 'GreaterThan': '', 'LessThan': '', 'NotEqualTo': '', 'EqualTo': '' })) {
var item = items.getItem(j); if (item != null)
item.set_visible(false);
}
else { var item = items.getItem(j); if (item != null) item.set_visible(true); } j++;
}
}
column = null;
menu.repaint();
}
function filterMenuShowing(sender, eventArgs) {
column = eventArgs.get_column();
}
</script>
</telerik:RadCodeBlock>
<telerik:RadGrid...>
//Additional markup removed
<FilterMenu OnClientShowing="MenuShowing" />
</telerik:RadGrid>
Explanation from Telerik:
There is a single filtering menu object server-side. Not all of its
items appear in every filter menu client-side....The filtering menu is independent for each
column in RadGrid - this means that the filtering menu options vary by
the DataType of the corresponding column....However, if you remove some of the options
from the menu on the server, this will affect all grid columns and
they will be stripped from each column filter menu options (if
available by default for that type of column).
Chambo solution can be customise to solve this exact problem.
In Js:
First as you need to access the Column Name, you can add it to the filterMenuShowing function. Or access it via get_uniqueName() on column.
var column = null;
var columnName = null;
function MenuShowing(sender, args) {
if (column == null) return;
if (columnName == null) return;
var menu = sender; var items = menu.get_items();
if (columnName == "Date") { // If the column name is Date
var i = 0;
while (i < items.get_count()) {
if (!(items.getItem(i).get_value() in { 'NoFilter': '', 'Contains': '', 'GreaterThan': '', 'LessThan': '' })) {
var item = items.getItem(i);
if (item != null){
item.set_visible(false);
}
}
else { // Not mandatory.
var item = items.getItem(i);
if (item != null){
item.set_visible(true);
}
} i++;
}
}
else {
if (columnName == "Name") {
var j = 0;
while (j < items.get_count()) {
if (!(items.getItem(j).get_value() in { 'NoFilter': '', 'Contains': '', 'StartsWith': '', 'EndsWith': '' })) {
var item = items.getItem(j);
if (item != null){
item.set_visible(false);
}
}
else { // Not mandatory.
var item = items.getItem(j);
if (item != null){
item.set_visible(true);
}
} j++;
}
}
}
column = null;
columnName = null;
}
function filterMenuShowing(sender, eventArgs) {
column = eventArgs.get_column();
columnName = eventArgs.get_column().get_uniqueName();
}
In Aspx:
You need to link your function to the right client event as show in the documentation.
<ClientSettings>
<Scrolling AllowScroll="false" />
<ClientEvents OnFilterMenuShowing="filterMenuShowing" />
</ClientSettings>
and
<FilterMenu OnClientShowing="MenuShowing" />

How to get files from onedrive in c#

We have a requirement that is we need to access onedirve through asp.net/C# and need to get the latest uploaded file..?
Please help me how to solve this type of requirement..?
i tried the following code..
i used following namespaces. but didn't work
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Filters;
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Models;
private LiveAuthClient MSAuthClient
{
get
{
if (this.liveAuthClient == null)
{
IDictionary<int, string> secretMap = new Dictionary<int, string>();
secretMap.Add(ClientSecretKey, ClientSecret);
this.liveAuthClient = new LiveAuthClient(ClientId, secretMap, null, this);
}
return this.liveAuthClient;
}
}
private MSAccountStatus MSAccountStatus
{
get
{
if (this.msAccountStatus == Controllers.MSAccountStatus.None)
{
using (UsersContext db = new UsersContext())
{
MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
this.msAccountStatus = msAccount != null ? MSAccountStatus.Connected : MSAccountStatus.NotConnected;
}
}
if (this.msAccountStatus == MSAccountStatus.Connected)
{
LiveConnectSession session = this.MSAuthClient.Session;
if (session == null || session.Expires < DateTimeOffset.UtcNow)
{
this.msAccountStatus = MSAccountStatus.ConnectedWithError;
}
}
return this.msAccountStatus;
}
}

Creating a new cookie (overwriting the old one) keeps a list of old values?

Edit: Sorry! I forgot to include details. I'm using C# within a MVC4 project.
so I have some code here that is supposed to
1. Create a new cookie if the UserID parameter is set and one hasn't been set already
2. if a cookie has not been set and no UserID parameter is specified, set the UserID to 1
3. if a new UserID parameter is there then update the cookie with the new UserID.
Problem is that ,If UserID is first set to Jake, then to Joe, then to Bob, I get a Cookie Value that looks like this "Bob, Joe, Jake". Is this normal? It seems like it'd be best to clear this list. Thanks in advance for your time.
public static void StoreID()
{
if ((HttpContext.Current.Request.Cookies["UserID"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] != null))
{
HttpContext.Current.Response.Cookies["UserID"].Value = System.Web.HttpContext.Current.Request.Params["UserID"];
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
else if ((HttpContext.Current.Request.Cookies["UserID"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
HttpContext.Current.Response.Cookies["UserID"].Value = "1";
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
else if ((HttpContext.Current.Request.Cookies["UserID"] != null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
}
else
{
HttpContext.Current.Response.Cookies["UserID"].Value = System.Web.HttpContext.Current.Request.Params["UserID"];
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
}
Ok, so introducing subkeys fixed the problem. Not sure why this works the way it does - if someone has any input on why that'd be great! Here's the working code:
if ((HttpContext.Current.Request.Cookies["UserInfo"]== null) && (System.Web.HttpContext.Current.Request.Params["UserID"] != null))
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = System.Web.HttpContext.Current.Request.Params["UserID"];
}
else if ((HttpContext.Current.Request.Cookies["UserInfo"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = "1";
}
else if ((HttpContext.Current.Request.Cookies["UserInfo"] != null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
}
else
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = System.Web.HttpContext.Current.Request.Params["UserID"];
}

how to get enableCrossAppRedirects with form authentication asp.net working?

has anyone come across this property? I am actually trying to implement a single sign on for 2 asp.net websites in a different domain. Looking for a sample code for this?
many thanks!
Have a peek at this page if you are using cross domain you'll need to make sure you use cookie-less authentication too since the cookies won't be cross domain.
Theres a nice code sample from a author of another Stack Question here.
if (FormsAuthentication.EnableCrossAppRedirects)
{
text = context.Request.QueryString[name];
if (text != null && text.Length > 1)
{
if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
{
cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);
}
try
{
formsAuthenticationTicket = FormsAuthentication.Decrypt(text);
}
catch
{
flag2 = true;
}
if (formsAuthenticationTicket == null)
{
flag2 = true;
}
}
if (formsAuthenticationTicket == null || formsAuthenticationTicket.Expired)
{
text = context.Request.Form[name];
if (text != null && text.Length > 1)
{
if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
{
cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);
}
try
{
formsAuthenticationTicket = FormsAuthentication.Decrypt(text);
}
catch
{
flag2 = true;
}
if (formsAuthenticationTicket == null)
{
flag2 = true;
}
}
}
}

regular expression asp.net

I trying to improve a textbox that filters a gridview, by implementing an enhanced textbox that can identify AND, OR, NOT operators by searching for this keywords in the string the user inputs in the textbox.
I am trying to do a regular expression to group the results but I'm not very good at this and I am failing to get what I want.
An example of what I want is as follows:
string = "build1 and build2 and build3 or build4 or not build5 and not build6"
results in a split mode:
build1 and
build2 and
build3 or
build4 or not
build5 and not
build6
This is because then I will take the first for example and replace with
SomeTable.Name_Of_Build = 'build1' AND
SomeTable.Name_Of_Build = 'build2' AND .... so on
This works for me
\w+(\sand\snot|\sor\snot|\sand|\sor|$)
I might recommend that instead of using a regular expression to group the results you do something like this. I think it would be more robust than trying to guess at the right regex.
string filter = "build1 and buil2 and build3 or build4 or not build5"
list<string> filterTokens = filter.Split(new char[] {' '})
string gridViewFilter = "";
bool notEqual = false;
foreach(string token in filterTokens)
{
if(token == "and")
{
gridViewFilter += "and"
}
else if(token == "or")
{
gridViewFilter += "or"
}
else if(token == "not")
{
notEqual = true;
}
else if(notEqual)
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
notEqual = false;
}
else
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
}
}
Also, if you really want to implement a robust and full featured sort you need to look into using Reverse Polish Notation (RPN). It would allow you to handle parentheses and order of operations. An RPN implementation would look something like this.
private bool CheckForFilterMatch(string filter, List<string> values, bool exactMatch)
{
for (int i = 0; i < values.Count; i++)
{
values[i] = values[i].ToLower();
}
if (filter.Trim() == "")
{
return true;
}
List<string> rpn = GetPostFixNotation(filter);
Stack<bool> output = new Stack<bool>();
foreach (string token in rpn)
{
if (IsValue(token))
{
bool isMatch;
if (exactMatch)
{
isMatch = values.Contains(token.ToLower());
}
else
{
isMatch = false;
foreach (string value in values)
{
isMatch = (value.IndexOf(token.ToLower()) != -1);
if (isMatch) break;
}
}
output.Push(isMatch);
}
else if (IsOperator(token))
{
bool operand1 = output.Pop();
bool operand2 = output.Pop();
if (token == "&")
{
output.Push(operand1 && operand2);
}
if (token == "|")
{
output.Push(operand1 || operand2);
}
}
}
return output.Pop();
}
public List<string> GetPostFixNotation(string filter)
{
if (filter == "")
{
return new List<string>();
}
List<string> postFixNotation = new List<string>();
Queue<string> output = new Queue<string>();
Stack<string> operators = new Stack<string>();
List<string> parsedFilter = ParseFilterTokens(filter);
foreach (string token in parsedFilter)
{
if (IsValue(token))
{
output.Enqueue(token);
}
else if (IsOperatorNoParenth(token))
{
while (operators.Count > 0 && IsOperatorNoParenth(operators.Peek()))
{
if ((operators.Count > 0 && (Precedence(token) <= Precedence(operators.Peek()))))
{
string operatorToReturn = operators.Pop();
output.Enqueue(operatorToReturn);
}
else break;
}
operators.Push(token);
}
else if (token == "(")
{
operators.Push(token);
}
else if (token == ")")
{
while (operators.Count > 0 && operators.Peek() != "(")
{
output.Enqueue(operators.Pop());
}
operators.Pop();
}
}
while (operators.Count > 0)
{
output.Enqueue(operators.Pop());
}
while (output.Count > 0)
{
postFixNotation.Add(output.Dequeue());
}
return postFixNotation;
}
Try this regex out:
(build[^b]+)

Resources