Basically we have quite a few fields within our member search.
We have a few optimized store procedures specifically for certain searches. For example if the user only searches by email address then it would use SearchMemberEmail however if it's search by postcode only then it would use SearchMemberPostcode.
This is all to do with the execution plan in sql server am told.
So we have a LONG ass if statement that basically checks if the the other text boxes are empty. i.e.
if(!string.isnullorempty(Email.Text) && string.isnullorempty(a.Text) && string.isnullorempty(b.Text)
{
Use SearMemberByemail stored procedure
}
The if statement is horrible and hard to read is there a better way of doing this?
You can combine the string.IsNullOrEmpty values to get one number which you can then act on. I only did this as a crude Windows Forms program which displays the intended action in a Label, but it shows the principle:
private void button1_Click(object sender, EventArgs e)
{
int choices = ((string.IsNullOrEmpty(uEmail.Text)) ? 0 : 1) +
((string.IsNullOrEmpty(uA.Text)) ? 0 : 2) +
((string.IsNullOrEmpty(uB.Text)) ? 0 : 4);
switch (choices)
{
case 1:
// search for email
label1.Text = "Email search";
break;
case 2:
// search for A
label1.Text = "A search";
break;
case 4:
// search for B
label1.Text = "B search";
break;
case 6:
// search for A+B
label1.Text = "A+B search";
break;
default:
// general search
label1.Text = "General search";
break;
}
}
Further options would use values of 8, 16, 32...
Related
I have one drop down list in my pages that its source comes of below code. Now I like to put 1 text box adjusted on my drop down list and when I type on that, source of drop down list (DocumentNo) depend on what I type in the text box and when text box is null drop downs list shows all the (DocumentNo) , please help how I have to change my code,
protected void ddlProjectDocument_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var query = from p in _DataContext.tblDocuments
orderby p.DocumentNo
select p;
int maxs = 0;
foreach (tblDocument v in query)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocument vv in query)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.TITLE;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle);
ddlProjectDocument.Items.Add(new ListItem(doctitle, vv.DocId.ToString()));
}
}
First, I would highly recommend storing the result of that query at the beginning of the method into something like a session variable so that you don't have to continually query the database every time you hit this page.
Second, you should use the OnTextChanged event in ASP.NET to solve this problem. Put in the OnTextChanged attribute to point to a method in your code behind that will grab the query result values (now found in your session variable) and will reset what is contained in ddlProjectDocument.Items to anything that matched what was being written by using String.StartsWith():
var newListOfThings = queryResults.Where(q => q.DocumentNo.StartsWith(MyTextBox.Value));
At this point all you need to do is do that same loop that you did at the end of the method above to introduce the correct formatting.
I'm trying to do a search on a table in my database where it returns the top 50 rows with a firstname like the search term being passed to the function, but its always returning the same 50 results
My sql looks like this:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
When I run this query in Visual Studios query window, it works as expected but when I run it through my ASP.NET application, it always returns the same 50 results, and only one of them has a first name close to the searchTerm I passed to it.
here is the page code that runs the function:
protected void Page_Load(object sender, EventArgs e)
{
_migrated_data data = new _migrated_data();
DataSet ds = data.Search(Request.QueryString.Get("query"), "A_RECID", 50);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
rpt_Data.DataSource = ds.Tables[0].DefaultView;
rpt_Data.DataBind();
}
}
and here is the search method of _migrated_data:
public DataSet Search(String #pSearchTerm, String #pSortBy, int #pRowCount)
{
DataSet ds = new DataSet();
OleDbConnection objOleDBConn;
OleDbDataAdapter objOleDBDa;
objOleDBConn = new OleDbConnection(ClearingHouse_OLEDDB);
objOleDBConn.Open();
string lSQL = "SELECT TOP(50) * FROM [database].[dbo].[records]";
lSQL += " WHERE (A_1STNAME LIKE #searchTerm ) ORDER BY #sortBy";
SqlCommand t = new SqlCommand(lSQL);
if (pSearchTerm != null && pSearchTerm != "")
{
t.Parameters.AddWithValue("#searchTerm", #pSearchTerm + "%");
}
if (pSortBy != null && pSortBy != "")
{
t.Parameters.AddWithValue("#sortBy", #pSortBy);
}
else
{
t.Parameters.AddWithValue("#sortBy", "A_RECID");
}
objOleDBDa = new OleDbDataAdapter(t.CommandText, objOleDBConn);
objOleDBDa.SelectCommand.CommandType = CommandType.Text;
objOleDBDa.Fill(ds);
objOleDBConn.Close();
return ds;
}
Using locals to view the final CommandText of t, I get the sql results I gave above.
Any help is greatly appriciated :)
AS Rob Rodi said, first of all, to get the results begining with a value you will need % char at the end of the therm:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
Second, probably your searchTerm is empty, so it's grabbing always the same results.
Debug your app and watch the variable to see if it's receiving some value.
You are having SQL injection there. Also it looks like the %-signs are missing.
The fact, that the query works in a query window and not in your app means, that the error is not in your query! Did you think about that? Probably, you should post code of your ASP.NET app.
It sounds like your parameter isn't being correctly passed to your data layer. Easiest way to find out if that's the case is to turn on Sql Profiler and check to see if it's being passed. If it is, your sql's to blame. If it's not, it's your application. You can then use the debugger on your application to work your way up the stack to see where the problem lies.
I'd like to insert all Labels from a labelModuleId in an AX2009 table.
I have this job, that does nearly everything I need. But I have to enter the max Id (toLabel = 1000):
static void OcShowAllLabel(Args _args)
{
xInfo xinfo;
LanguageId currentLanguageId;
LabelModuleId labelModuleId = 'OCM'; // hier evt eine Eingabe durch Benutzer zur Auswahl
LabelIdNum frLabel;
LabelIdNum toLabel = 1000;
LabelId labelId;
OcShowAllLabels_RS tab;
Label blub = new Label();
str label;
;
xInfo = new xInfo();
currentLanguageId = xInfo.language();
delete_from tab
where tab.LanguageId == currentLanguageId
&& tab.LabelModuleId == labelModuleId;
for (frLabel = 1; frLabel <= toLabel; frLabel++)
{
labelId = strfmt('#%1%2', labelModuleId, frLabel);
label = SysLabel::labelId2String(labelId, currentLanguageId);
if (labelId != label)
{
tab.initValue();
tab.LabelId = labelId;
tab.Label = label;
tab.LanguageId = currentLanguageId;
tab.LabelModuleId = labelModuleId;
tab.insert();
}
}
Info('done');
}
If this is a one-time job, you can just stop the AOS and open the label file in notepad. It's in your application folder called axXXXen-us.ald, where XXX is your label file name and en-us is your language.
Look at classes\Tutorial_ThreadWork\doTheWork to see where they use a while(sLabel) instead of a for loop like you have.
container doTheWork(Thread t,LabelType searchFor)
{
container retVal;
SysLabel sysLabel = new SysLabel(LanguageTable::defaultLanguage());
str slabel;
;
slabel = sysLabel.searchFirst(searchFor);
while (slabel)
{
retVal += sLabel;
slabel = sysLabel.searchNext();
}
return retVal;
}
Since the label file is a text file, it would make sense that you can't just select the last one, but you have to iterate through the file. AX caches the labels however, but I don't believe you can just readily access the label cache as far as I know.
Lastly, hopefully you won't try this, but don't try to just read in the label text file, because AX sometimes has labels that it hasn't flushed to that file from the cache. I think Label::Flush(...) will flush them, but I'm not sure.
Here is another option I suppose. You can insert a label to get the next label number and then just immediately delete it:
static void Job32(Args _args)
{
SysLabel sysLabel = new SysLabel(LanguageTable::defaultLanguage());
SysLabelEdit sysLabelEdit = new SysLabeLEdit();
LabelId labelid;
;
labelId = syslabel.insert('alextest', '', 'OCM');
info(strfmt("%1", labelId));
sysLabelEdit.labelDelete(labelId, false);
}
It does seem to consume the number from the number sequence though. You could just do a Label::Flush(...) and then check the text file via code. Look at Classes\SysLabel* to see some of how the system deals with labels. It doesn't look very simple by any means.
Here is another option that might work for you. This will identify missing labels too. Change 'en-us' to your language. This is a "dirty" alternative I suppose. You might need to add something to say "if we find 5 labels in a row where they're like '#OCM'".
for (i=1; i<999; i++)
{
labelId = strfmt("#%1%2", 'OCM', i);
s = SysLabel::labelId2String(labelId, 'en-us');
if (s like '#OCM*')
{
info (strfmt("%1: Last is %2", i, s));
break;
}
info(strfmt("%1: %2", i, s));
}
I have a switch statement in my action script class.I have a function onKeyDown(event: KeyboardEvent) which contain a switch statement.which control the different keys.
But now I want to handle the same functionality which TAB key is doing using two keys CTRL and SPACE key.
I want add a case more in my switch statement first I pressed CTRL and then SPACE key then a a specific function is called.
Anyone can tell me how two keys used in my switch statement?
private function onKeyDown(event: KeyboardEvent) : void{
if (popUp.displayPopUp){
switch (event.keyCode){
case Keyboard.UP:
case Keyboard.DOWN:
case Keyboard.END:
case Keyboard.HOME:
case Keyboard.PAGE_UP:
case Keyboard.PAGE_DOWN:
inputTxt.selectRange(text.length, text.length)
list.dispatchEvent(event)
break;
case Keyboard.ENTER:
acceptCompletion();
break;
case Keyboard.TAB:
if (requireSelection)
acceptCompletion();
else
popUp.displayPopUp = false
break;
case Keyboard.ESCAPE:
popUp.displayPopUp = false
break;
case Keyboard.CONTROL && Keyboard.SPACE:
if (requireSelection)
acceptCompletion();
else
popUp.displayPopUp = false
break;
}
}
}
This is a pretty common problem.
event.keyCode is only going to give you the keyCode for the most recent key pressed. So you will have to store key presses and key releases. Fortunately, AS3 is a pretty sweet Array implementation that allows this to be done easily.
var _keys:Array;
addEventListener(KeyboardEvent.KEY_DOWN, keyDownEvent);
addEventListener(KeyboardEvent.KEY_UP, keyUpEvent);
function keyDownEvent(e:KeyboardEvent)
{
// turn the key on
_keys[e.keyCode] = true;
// perform logic
keyLogic()
}
function keyUpEvent(e:KeyboardEvent)
{
// turn the key off
_keys[e.keyCode] = false;
}
function keyLogic()
{
// this is where the actual logic is
if(_keys[Keyboard.SPACE] && _keys[Keyboard.CONTROL])
{
if (requireSelection)
acceptCompletion();
else
popUp.displayPopUp = false
}
}
This allows you to have a neat little array that always tells you what keys are down. It also separates your program logic from your input logic. Double win.
In your case you can just check ctrlKey property on KeyboardEvent. But #DingoEatingFuzz's answer will allow check combinations like 'space' + 'letter' and so on.
case Keyboard.SPACE:
if (event.ctrlKey)
{
}
break;
i think this one approch is good........
Look please below this codes throw me : FormatException was unhandled by user code
Codes:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
How can i rewrite linq query?
You are calling ToString on the query rather than a single result. Even though you may expect only one value to match your query, it will not return just a single value. You have to instruct it to do so using Single, First, Last or the variations of these that also return a default value (SingleOrDefault, FirstOrDefault, LastOrDefault).
In order to avoid an exception, you could change it to use Decimal.TryParse or you could change your code to use a default value if the LINQ query returns something that won't parse properly. I'd recommend the former or a combination.
Note that in the following example, I have added the call to SingleOrDefault. This ensures that only one value is parsed, even if no value is found, and that if there are multiple results, we get an exception (i.e. it enforces that we get exactly zero or one result to the query).
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
You're calling ToString() on an IQueryable<T> - what did you expect the string to be? It's very unlikely to be anything which can be parsed as a decimal number!
My guess is that you want to call First() or Single(), but we can't really tell without more information. What's the type of o.Kdv?
I suspect you either want:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
or
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
When I use debug mode I see the data is update when over mouse, after end of this method ( it's show this message [input string was not in a correct format]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }