ICallbackEventHandler, RaiseCallbackEvent not firing - c#

I have the following Javascript:
function processText(n)
{
CallServer("1" + n.id + "&" + n.value, "");
}
function ReceiveServerData(arg, context)
{
alert(arg);
}
With this for my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbRef = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackscript = "function CallServer(arg, context) {" + cbRef + "; }";
cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackscript, true);
if (Request.QueryString["stationID"] != null)
{
isIndividual = true;
stationID = Request.QueryString["stationID"];
EncodeDecode objServers = new EncodeDecode(HttpContext.Current.Server.MapPath("~/App_Data/"));
if (!IsPostBack)
{
List<IServerConfig> serverConfig = objServers.GetServerConfiguration(stationID);
Session["ServerConfig"] = serverConfig;
Session["dctPropertyControls"] = new Dictionary<string, PropertyObj>();
}
BindDynamicControls(Session["ServerConfig"] as List<IServerConfig>);
}
}
public void RaiseCallbackEvent(String eventArgument)
{
int iTyped = int.Parse(eventArgument.Substring(0, 1).ToString());
if (iTyped != 0) //Process Text Fields
{
string controlName = eventArgument.Substring(1, eventArgument.IndexOf("&")).ToString();
string controlValue = eventArgument.Substring(eventArgument.IndexOf("&")).ToString();
//Txtid += -1;
Dictionary<string, PropertyObj> dctPropertyObj = Session["dctPropertyControls"] as Dictionary<string, PropertyObj>;
PropertyObj propertyObj = dctPropertyObj[controlName];
propertyObj.property.SetValue(propertyObj.owner, controlValue, null);
this.sGetData = "Done";
}
}
public String GetCallbackResult()
{
return this.sGetData;
}
processText gets fired and works, however RaiseCallbackEvent never fires. Any ideas?

Apparently, any sort of validation error will cause this, though the page will never tell you about it. In my case, I had two datalists on the page with the same id. I had to debug the javascript and read the xmlRequest to see the error.

Sorry if replying late but may help others..
ValidationRequest="false" at .aspx page may sort out this unidentified problem.

Related

AutoComplete on a TextBox ignoring accentuation

I have a custom TextBox control (It is a custom one instead of a regular one to be able to have hint text on top of it), in which I have an AutoComplete that gets it's data from my DB using a DataSet like this
string[] postSource = aux.Tables[0].AsEnumerable().Select<System.Data.DataRow, String>(x => x.Field<String>("nm_industria")).ToArray();
var source = new AutoCompleteStringCollection();
source.AddRange(postSource);
txb_regClientData.AutoCompleteCustomSource = source;
txb_regClientData.AutoCompleteMode = AutoCompleteMode.Suggest;
txb_regClientData.AutoCompleteSource = AutoCompleteSource.CustomSource;
It gives me this result
Image if I type "João" it will give me the correct result, but if I type "Joao" it will not show up, from some reading on the matter I know that theres nothing in the AutoComplete to automatically ignore accentuation, so I will need to code it myself. My question is, where do I begin with this? My ideal solution would be to override something in the AutoComplete code of my custom control, I gave a read on the documentation for TextBox and couldn't find anything, so if anyone can show me the right direction so I can read and learn how to do this, would be highly appreciated.
There's still improvements to be done, but this code implements the solution for this, it "appends" a listBox to the textBox, there will be issues when multiple of these exist due to naming, but this should be a good starting point/reference for someone looking for something similar.
public class ExTextBox : TextBox
{
private bool alreadyRun = false;
ListBox suggestions = new ListBox();
int maxSize = 10;
string[] source;
public string Hint
public int MaxSuggestionBoxSize
{
get { return maxSize; }
set { maxSize = value; this.Invalidate(); }
}
protected override void OnCreateControl()
{
if (alreadyRun == false) // This is only supposed to be run once, but in some situations depending on the design of the main form,
{// this might need to be somewhere that gets called multiple times, this variable makes so this code is only run once even in those situations
suggestions.Name = "suggList_" + this.Name;
suggestions.Location = new Point(this.Location.X, (this.Location.Y + this.Size.Height));
suggestions.Size = new Size(this.Size.Width, this.Size.Height);
this.Parent.Controls.Add(suggestions);
this.Parent.Controls["suggList_" + this.Name].MouseDoubleClick += suggList_MouseDoubleClick;
this.Parent.Controls["suggList_" + this.Name].Hide();
alreadyRun = true;
}
base.OnCreateControl();
}
private void suggList_MouseDoubleClick(object sender, System.EventArgs e)
{
this.Text = this.Parent.Controls["suggList_" + this.Name].Text;
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
if(source != null) // Makes sure this code is only executed when the suggestion box is being used, by checking the existance of the source
{
try
{
if (this.Parent.Controls["suggList_" + this.Name].Focused == false)
{
this.Parent.Controls["suggList_" + this.Name].Hide();
}
}
catch
{
}
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
AutoCompleteSmart();
}
public void AutoCompleteSmart()
{
if (source != null)
{
suggestions.Items.Clear();
if (this.Text != "")
{
foreach (string a in source)
{
if (RemoveDiacritics(a.ToLower()).Contains(RemoveDiacritics(this.Text.ToLower())))
{
suggestions.Items.Add(a);
}
}
this.Parent.Controls.Remove(suggestions);
if (suggestions.Items.Count < maxSize) // Optional code, defines a limit size for the suggestion box
{
suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * suggestions.Items.Count) + suggestions.ItemHeight));
}
else
{
suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * maxSize) + suggestions.ItemHeight));
}
this.Parent.Controls.Add(suggestions);
this.Parent.Controls["suggList_" + this.Name].BringToFront();
this.Parent.Controls["suggList_" + this.Name].Show();
}
else
{
this.Parent.Controls["suggList_" + this.Name].Hide();
}
}
}
public void AutoCompleteSmartSource(string[] _source)
{
source = _source;
}
private static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
}

Could not find file 'c:\windows\system32\inetsrv\

I am using a aspx webpage with C# and I'm trying to point to a directory but when I do so, I get "Could not find file 'c:\windows\system32\inetsrv\2.txt'." But in my C# code, I am using:
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
This code should point to C:\inetpub\wwwroot\admin\applications
Anyone know why or how this is happening? Thanks ahead of time.
Additional Code:
string currentStaffPosition = null;
string currentStaffDirectory = null;
protected void rolesRadioButton_SelectedIndexChanged(object sender, EventArgs e)
{
dropDownList.Items.Clear();
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
string[] staffApplications = Directory.GetFiles(currentStaffDirectory);
foreach (string apps in staffApplications)
{
dropDownList.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(apps)));
}
}
protected void dropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
string currentSelectedApp = currentStaffDirectory + dropDownList.SelectedItem + ".txt";
string currentLine;
StreamReader applicationReader = new StreamReader(currentSelectedApp);
while ((currentLine = applicationReader.ReadLine()) != null)
{
if (currentLine.Contains("First Name:"))
forumUsernameTextBox.Text = currentLine.Replace("First Name: ", "");
}
applicationReader.Close();
}

Removing text when onSelectedChange Occurs

I am just wondering if anyone could give me indication as to how to remove a piece of text if a statement is not satisfied after onSelectedChange event.
My code,
protected void currency_SelectedIndexChanged(object sender, EventArgs e)
{
if (stm_currency.SelectedItem != null)
{
lblResults.Text = "" +
stm_merchant.SelectedItem.Text + " statement for " +
stm_month.SelectedItem.Text + " " +
stm_year.SelectedItem.Text;
}
else
{
lblResults.Text.Remove(0);
}
}
change this line of code
lblResults.Text = "";
It would set it to be an empty string.
The remove method returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
http://msdn.microsoft.com/en-us/library/d8d7z2kk(v=vs.110).aspx
You should use lblResults.Text = ""; or lblResults.Text = string.Empty;
You should check to see if the label needs invoked first.
delegate void setLabelText(string s);
public void invokeSetLabelText(string s)
{
if (this.lblResults.InvokeRequired)
{
setLabelText d = new setLabelText(invokeSetLabelText);
this.Invoke(d, new object[] { s });
}
else
lblResults.Text = s;
}
protected void currency_SelectedIndexChanged(object sender, EventArgs e)
{
if (stm_currency.SelectedItem != null)
invokeSetLabelText(string.Format("{0} statement for {1} {2}",
stm_merchant.SelectedItem.Text,
stm_month.SelectedItem.Text,
stm_year.SelectedItem.Text));
else
invokeSetLabelText(string.Empty);
}

Better approach in C# to search data on a third party web site

Here's my requirement. There is a public website which takes alphanumeric string as input and Retrieves data into a table element (via button click). The table element has couple of labels which gets populated with corresponding data. I need a tool/solution which can check if a particular string exists in the website's database. If so retrieve all the Ids of all the occurrences of that string. Looking at the "view source" of the website (No JavaScript used there), I noted the input element name and the button element name and with the help of existing samples I was able to get a working solution. Below is the code which works but I want to check if there is any better and faster approach. I know the below code has some issues like "infinite loop" issue and others. But I am basically looking at alternate solution which can work quickly for a million records.
namespace SearchWebSite
{
public partial class Form1 : Form
{
bool searched = false;
long i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = null;
if (searched == false)
{
b = (WebBrowser)sender;
b.Document.GetElementById("txtId").InnerText = "M" + i.ToString();
b.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
if (b.ReadyState == WebBrowserReadyState.Complete)
{
if (b.Document.GetElementById("lblName") != null)
{
string IdNo = "M" + i.ToString();
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
{
using (StreamWriter w = File.AppendText("log.txt"))
{
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
}
}
}
If the page after seach button clicked contains txtId and btnSearch controls than you can use this code snippet, this is not faster but the correct form I think.
public partial class Form1 : Form
{
bool searched = false;
long i = 1;
private string IdNo { get { return "M" + i.ToString(); } }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
if (b.ReadyState == WebBrowserReadyState. Complete)
{
if (searched == false)
{
DoSearch(b); return;
}
if (b.Document.GetElementById("lblName") != null)
{
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
using (StreamWriter w = File.AppendText("log.txt"))
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
}
i++;
DoSearch(b);
}
}
private void DoSearch(WebBrowser wb)
{
wb.Document.GetElementById("txtId").InnerText = IdNo;
wb.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
}

DropDownList1.SelectedValue is null?

I cannot get anything other than a null value from my drop down box, im trying to upload files to different directories...
public class dropDownInfo
{
public string pathName { get; set; }
public string pathValue { get; set; }
}
string uploadFolder = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// reference to directory
//DirectoryInfo di = new DirectoryInfo("//DOCSD9F1/TECHDOCS/");
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files/");
// create list of directories
List<dropDownInfo> DropDownList = new List<dropDownInfo>();
foreach (DirectoryInfo i in di.GetDirectories())
{
dropDownInfo ddInfo = new dropDownInfo();
ddInfo.pathName = i.FullName;
ddInfo.pathValue = i.FullName;
DropDownList.Add(ddInfo);
}
DropDownList1.DataSource = DropDownList;
DropDownList1.DataTextField = "pathName";
DropDownList1.DataValueField = "pathValue";
DropDownList1.DataBind();
}
}
protected void DropDownList1_IndexChanged(object sender, EventArgs e)
{
uploadFolder = DropDownList1.SelectedItem.Value;
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
//string uploadFolder = DropDownList1.SelectedValue;
//string path = (uploadDirectory + uploadFolder + "/" + fileName);
string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
Do a check before you access the Value property.
if (DropDownList1.SelectedItem != null)
uploadFolder = DropDownList1.SelectedItem.Value;
The dropdown has no values after postback. You are only binding at first page load, then the page posts back (index changed) and the items are not re-bound.
Do you have viewstate disabled on the page or any of the controls? This could cause the issue you are describing.
Also, the local variable uploadFolder will never be preserved between post backs. You need to store it in the session or on the page somewhere.
Session["uploadFolder"] = DropDownList1.SelectedItem.Value
You need to re-set the DataSource on post back, but don't re-bind it or that will reset the selected index as well.

Categories

Resources