How to show a message from webmethod? - c#

Friends,I need a help regarding showing error message or any other message in web method. I tried with writing some function to show message if the return value is "0" or the return string variable's length is "0" but no result. Can you give some solution to this?
Yes, sure. Here is my code:-
[WebMethod]
public string[] GetCompletionCompany(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText != "")
{
strSQLQuery = "SELECT ID," +
" stallno," +
" company " +
"FROM IESS2012_IND_PartDetails " +
"WHERE company LIKE '%" + prefixText + "%' " +
"ORDER BY company";
}
DataTable dt = objDBHelper.gReturnDataSet(System.Data.CommandType.Text, strSQLQuery).Tables[0];
List<string> items = new List<string>(count);
for (int i = 0; i < dt.Rows.Count; i++)
{
string strName = dt.Rows[i][2].ToString();
items.Add(strName);
}
if (items.ToArray().Length == 0)
{
ShowMessage();
return items.ToArray();
}
else
{
return items.ToArray();
}
}
private void ShowMessage()
{
string msg= gUserMessage.NoRecords;
return msg;
}
How will I show the message that there is no record?

If you want to show the Error Message on Client Side you can just throw an appropriate Exception - SOAP will encapsulate it and you get a SOAP-Error on the client side containing the exception message.
So on the Server side:
if (items.ToArray().Length == 0)
{
throw new NoRecordsException("Your Message...");
}
and on the client side (assuming you are using C# too):
string[] result;
try
{
result = service.GetCompletionCompany(prefixText, count);
}
catch(SoapException exp)
{
string message = exp.Message; //or exp.InnerException.Message
}

Related

Looping through arrays in asp.net is not working

I have an array which sometimes holds values like "ABC, XYZ, TTT" and sometime only "ABC"
So while iterating through the arrays when it holds multiple it checks only for the first item and not the other item.
string[] strStateArray = new string[] { "" };
strStateArray = strOne.Split(',');
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].ToString()) // not checking for multiple items
{
}
}
updated code
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].Trim().ToString())
{
if (dt.Rows.Count > 0)
{
dt.TableName = "RecodSet";
string xml = ConvertDatatableToXML(dt);
mycon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('File uploaded successfully.!!');", true);
// System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('File uploaded successfully.!!');", true);
}
else
{
string noData = "No data to upload.";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", noData, false);
}
}
else
{
string file_name = fluUploadBtn.FileName;
if ((System.IO.File.Exists(file_name)))
{
System.IO.File.Delete(file_name);
}
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('User is not authorised to upload data for state mentioned in excel report ');", true);
}
}
Could you just go debug the value then?
let me rewrite some code for you
String logMsg ="";
String targetKeyword = dt.Rows[0]["CIRCLE"].ToString();
for (int i = 0; i < strStateArray.Length; i++)
{
String tmp_Val_Pure = strStateArray[i] ==null? null : strStateArray[i].ToString(); //debug here see the value1
String tmp_Val = strStateArray[i] ==null? "" : strStateArray[i].ToString().Trim(); //debug here see the value2
bool isThisOk = (targetKeyword == tmp_Val ); //debug here see the val of isThisOk
if ( isThisOk )
{
logMsg += "Success Record : "+ i.ToString() + " val : " + tmp_Val ;
if (dt.Rows.Count > 0)
{ // alert case OK
} else { // alert no val dt }
}
else
{
logMsg += "Err Record : "+ i.ToString() + " val : " + tmp_Val ;
}
} //end loop
//Go check logMsg

How to refactor code duplication inside static class?

Below is a section of code that is part of a static class that is giving me trouble refactoring. I've spent a few weeks thinking about ways of approaching this but have been unsuccessful thus far.
Some context - this is part of a TCP Server I'm working on. The TCP Server behaves similar to the websocket specification - when a new client connects, all the management of the client socket is abstracted away, and instead simple callbacks are exposed which can be registered to subscribers.
ie. OnReceived, OnConnect, OnDisconnect, OnSend
This way I can have another class subscribe to the behaviors required from the socket client and keep the responsibilities of managing the socket and business logic separate. Whenever the client socket receives data, it reads the entire data block and then raises the 'OnReceived' callback method, passing in the received data.
The purpose of all of this is to read various requests from a Lua client and perform the appropriate action. Some actions will go to a MySQL Database (via calling stored procedure and passing the request data as arguments to the sproc). There is also the added flexibility of being able to send more than a single dataset in the request, meaning fewer request/responses need to be sent between client and server.
This has been great for many months and has made it very easy to maintain and change the business code without needing to worry about breaking the socket behavior. If I needed to change a stored procedure in a database, it only required updating the database and the Lua client code, as the TCP Server does not care about these implementation details.
However, now there is a new requirement which is to support both MySQL and Redis, and for the TCP Server to be able to direct the request to either of these sources in a flexible way.
The first issue of duplication is the ProtocolResponseSingleData and ProtocolResponseMultiData structs - these structures are almost identical, except for the 'Data' property. I need to be able to return either a single data set, or a collection of data sets. Both of these classes are serialized into a JSON string. This has caused duplication with SendToDBSingleData and SendToDBMultiData methods.
struct ProtocolResponseMultiData
{
public string Action;
public bool Result;
public string Error;
public List<List<object>> Data;
}
struct ProtocolResponseSingleData
{
public string Action;
public bool Result;
public string Error;
public List<object> Data;
}
The second issue is there are 4 methods which are very similar to each other in ways - SendToMySQLDBSingleData, SendToMySQLDBMultiData, SendToRedisDBSingleData, SendToRedisDBMultiData. I just can't seem to figure out how to collapse these down to 1 or 2 methods at most.
The third issue is this class is all static methods - the socket client exposes callbacks, but it is not aware of any particular instance of an object, hence the callbacks need to be declared static. This makes it difficult to apply things like Strategy and Factory patterns to simplify the design.
Is there any hope for me?
public static void OnReceived(object sender, IPCReceivedEventArgs e)
{
try
{
LogToFile(e.data, ((SocketClient)(sender)).LogFile);
Console.WriteLine("Received data from client (" + ((SocketClient)(sender)).Address + ")");
dynamic j = Newtonsoft.Json.JsonConvert.DeserializeObject(e.data);
// Verify the request format is valid
if (j["Action"] != null && j["BulkQuery"] != null && j["Data"] != null && j["Destination"] != null)
{
ProtocolRequest request = new ProtocolRequest
{
Action = j["Action"],
Destination = j["Destination"],
IPAddress = ((SocketClient)(sender)).Address,
LogPath = ((SocketClient)(sender)).LogFile
};
bool isBulkQuery = j["BulkQuery"];
string jsonResp = "";
if (isBulkQuery)
{
ProtocolResponseMultiData resp = SendToDBMultiData(request, ref j);
jsonResp = JsonConvert.SerializeObject(resp);
}
else
{
ProtocolResponseSingleData resp = SendToDBSingleData(request, ref j);
jsonResp = JsonConvert.SerializeObject(resp);
}
((SocketClient)(sender)).Write(jsonResp);
}
else
{
// send malformed request response
string jsonResponse = "{ \"Action\" : " + j["Action"] + ", \"Result\" : false, \"Error\" : \"Malformed Request Received\", \"Data\" : null }";
((SocketClient)(sender)).Write(jsonResponse);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception encountered during OnReceived handler: " + ex.Message);
LogToFile("Exception encountered during OnReceived handler: " + ex.Message, ((SocketClient)(sender)).LogFile);
string jsonResponse = "{ \"Action\" : \"UNKNOWN\", \"Result\" : false, \"Error\" : \"Malformed JSON Request Received\", \"Data\" : null }";
((SocketClient)(sender)).Write(jsonResponse);
}
finally
{
}
}
public static ProtocolResponseSingleData SendToDBSingleData(ProtocolRequest request, ref dynamic j)
{
if (request.Destination == "MYSQL")
{
return SendToMySQLDBSingleData(request, ref j);
}
else if (request.Destination == "REDIS")
{
return SendToRedisDBSingleData(request, ref j);
}
else
{
ProtocolResponseSingleData response = new ProtocolResponseSingleData
{
Action = request.Action,
Error = "Invalid Destination specified - must be either 'REDIS' or 'MYSQL'",
Data = null,
Result = false
};
return response;
}
}
public static ProtocolResponseMultiData SendToDBMultiData(ProtocolRequest request, ref dynamic j)
{
if (request.Destination == "MYSQL")
{
return SendToMySQLDBMultiData(request, ref j);
}
else if (request.Destination == "REDIS")
{
return SendToRedisDBMultiData(request, ref j);
}
else
{
ProtocolResponseMultiData response = new ProtocolResponseMultiData
{
Action = request.Action,
Error = "Invalid Destination specified - must be either 'REDIS' or 'MYSQL'",
Data = null,
Result = false
};
return response;
}
}
private static ProtocolResponseSingleData SendToMySQLDBSingleData(ProtocolRequest request, ref dynamic j)
{
// serialize a new json string for just the data by itself
string jdataString = Newtonsoft.Json.JsonConvert.SerializeObject(j["Data"]);
// now deserialize this string into a list of dictionaries for parsing
Dictionary<string, object> dataDictionary = null;
if (((JToken)j["Data"]).Type == JTokenType.Object)
dataDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(jdataString);
else
dataDictionary = new Dictionary<string, object>();
ProtocolResponseSingleData result = new ProtocolResponseSingleData
{
Action = request.Action,
Error = "",
Data = new List<object>(),
Result = false
};
// special scenario - because we cant get the ip address of the game server from DCS, we'll get it from the socket sender object
// and specially insert it as a parameter into the data dictionary
// the other special scenario is the server description request can supply - this can contain harmful html, so we must sanitize the input
if (request.Action == ACTION_GET_SERVERID)
{
dataDictionary.Add("IP", request.IPAddress);
if (dataDictionary.ContainsKey("Description"))
{
try
{
string html = Convert.ToString(dataDictionary["Description"]);
html = System.Web.HttpUtility.HtmlEncode(html);
dataDictionary["Description"] = SanitizeHTML(html);
}
catch (Exception ex)
{
LogToFile("Error sanitizing ServerDescription html string (Action: " + request.Action + ") - " + ex.Message, request.LogPath);
result.Error = "Error sanitizing ServerDescription html string (Action: " + request.Action + ") - " + ex.Message;
return result;
}
}
}
MySql.Data.MySqlClient.MySqlConnection _conn = null;
MySql.Data.MySqlClient.MySqlDataReader rdr = null;
try
{
_conn = new MySql.Data.MySqlClient.MySqlConnection(Config.MySQLDBConnect);
_conn.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(request.Action)
{
Connection = _conn,
CommandType = System.Data.CommandType.StoredProcedure
};
foreach (var d in dataDictionary)
{
if (d.Value.GetType() == typeof(Int64) && (Int64)d.Value == LUANULL)
cmd.Parameters.AddWithValue(d.Key, null);
else
cmd.Parameters.AddWithValue(d.Key, d.Value);
}
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
for (int i = 0; i < rdr.FieldCount; i++)
{
result.Data.Add(rdr[i]);
}
}
rdr.Close();
_conn.Close();
result.Result = true;
}
catch (Exception ex)
{
LogToFile("Error executing query against MySQL (Action: " + request.Action + ") - " + ex.Message, request.LogPath);
result.Error = "Error executing query against MySQL (Action: " + request.Action + ") - " + ex.Message;
}
finally
{
if (_conn != null)
if (_conn.State == System.Data.ConnectionState.Open || _conn.State == System.Data.ConnectionState.Connecting)
_conn.Close();
if (rdr != null)
if (!rdr.IsClosed)
rdr.Close();
}
return result;
}
private static ProtocolResponseMultiData SendToMySQLDBMultiData(ProtocolRequest request, ref dynamic j)
{
// serialize a new json string for just the data by itself
string jdataString = Newtonsoft.Json.JsonConvert.SerializeObject(j["Data"]);
// now deserialize this string into a list of dictionaries for parsing
List<Dictionary<string, object>> dataDictionary =
Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jdataString);
ProtocolResponseMultiData result = new ProtocolResponseMultiData
{
Action = request.Action,
Error = "",
Data = new List<List<object>>(),
Result = false
};
MySql.Data.MySqlClient.MySqlConnection _conn = null;
MySql.Data.MySqlClient.MySqlDataReader rdr = null;
try
{
foreach (var d in dataDictionary)
{
_conn = new MySql.Data.MySqlClient.MySqlConnection(Config.MySQLDBConnect);
_conn.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(request.Action)
{
Connection = _conn,
CommandType = System.Data.CommandType.StoredProcedure
};
foreach (var kv in d)
{
if (kv.Value.GetType() == typeof(Int64) && (Int64)kv.Value == LUANULL)
cmd.Parameters.AddWithValue(kv.Key, null);
else
cmd.Parameters.AddWithValue(kv.Key, kv.Value);
}
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
List<object> result_set = new List<object>();
for (int i = 0; i < rdr.FieldCount; i++)
{
result_set.Add(rdr[i]);
}
result.Data.Add(result_set);
}
else
{
result.Error += "No Results Returned\n";
}
rdr.Close();
_conn.Close();
}
result.Result = true;
}
catch (Exception ex)
{
LogToFile("Error executing query against MySQL (Action: " + request.Action + ") - " + ex.Message, request.LogPath);
result.Error = "Error executing query against MySQL (Action: " + request.Action + ") - " + ex.Message;
}
finally
{
if (_conn != null)
if (_conn.State == System.Data.ConnectionState.Open || _conn.State == System.Data.ConnectionState.Connecting)
_conn.Close();
if (rdr != null)
if (!rdr.IsClosed)
rdr.Close();
}
return result;
}
private static ProtocolResponseSingleData SendToRedisDBSingleData(ProtocolRequest request, ref dynamic j)
{
// Serialize the JSON Data property into its own JSON String
string jdataString = Newtonsoft.Json.JsonConvert.SerializeObject(j["Data"]);
// now deserialize this string into a list of dictionaries for parsing
Dictionary<string, object> dataDictionary = null;
if (((JToken)j["Data"]).Type == JTokenType.Object)
dataDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(jdataString);
else
dataDictionary = new Dictionary<string, object>();
ProtocolResponseSingleData result = new ProtocolResponseSingleData
{
Action = request.Action,
Error = "",
Data = new List<object>(),
Result = false
};
if (!RedisConnection.IsConnected)
{
LogToFile("Connection to Redis Closed - Attempting to reopen...", request.LogPath);
try
{
RedisConnection = ConnectionMultiplexer.Connect(Config.RedisDBConnect);
}
catch (Exception ex)
{
LogToFile("Error connecting to Redis - lost connection (" + ex.Message + ")", request.LogPath);
result.Error = "Error connecting to Redis - lost connection (" + ex.Message + ")";
return result;
}
}
try
{
string serverid = Convert.ToString(dataDictionary["ServerID"]);
string rediskey = Config.RedisActionKeys[request.Action];
if (serverid == null)
{
result.Error = "Error executing query against Redis (Action: " + request.Action + ") - " + "'ServerID' not found in Data request";
return result;
}
if (rediskey == null)
{
result.Error = "Error executing query against Redis - Action: '" + request.Action + "' not found in server configuration - please check action message or server configuration.";
return result;
}
IDatabase db = RedisConnection.GetDatabase();
string k = rediskey + ":" + serverid;
if (!db.StringSet(k, jdataString))
{
result.Error = "Failed to Set Key in Redis (Key: '" + k + "')";
}
else
{
result.Data.Add(1);
result.Result = true;
}
}
catch (Exception ex)
{
LogToFile("Error executing query against Redis (Action: " + request.Action + ") - " + ex.Message, request.LogPath);
result.Error = "Error executing query against Redis (Action: " + request.Action + ") - " + ex.Message;
}
return result;
}
private static ProtocolResponseMultiData SendToRedisDBMultiData(ProtocolRequest request, ref dynamic j)
{
// serialize a new json string for just the data by itself
string jdataString = Newtonsoft.Json.JsonConvert.SerializeObject(j["Data"]);
// now deserialize this string into a list of dictionaries for parsing
List<Dictionary<string, object>> dataDictionary =
Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jdataString);
ProtocolResponseMultiData result = new ProtocolResponseMultiData
{
Action = request.Action,
Error = "",
Data = new List<List<object>>(),
Result = false
};
if (!RedisConnection.IsConnected)
{
LogToFile("Connection to Redis Closed - Attempting to reopen...", request.LogPath);
try
{
RedisConnection = ConnectionMultiplexer.Connect(Config.RedisDBConnect);
}
catch (Exception ex)
{
LogToFile("Error connecting to Redis - lost connection (" + ex.Message + ")", request.LogPath);
result.Error = "Error connecting to Redis - lost connection (" + ex.Message + ")";
return result;
}
}
try
{
int id = 0;
foreach (Dictionary<string, object> x in dataDictionary)
{
id += 1;
string serverid = Convert.ToString(x["ServerID"]);
string rediskey = Config.RedisActionKeys[request.Action];
if (serverid == null)
{
result.Error = "Error executing query against Redis (Action: " + request.Action + ") - " + "'ServerID' not found in Data request";
return result;
}
if (rediskey == null)
{
result.Error = "Error executing query against Redis - Action: '" + request.Action + "' not found in server configuration - please check action message or server configuration.";
return result;
}
IDatabase db = RedisConnection.GetDatabase();
string k = rediskey + ":" + serverid + ":" + id;
string jdatastring = Newtonsoft.Json.JsonConvert.SerializeObject(x);
if (!db.StringSet(k, jdatastring))
{
result.Error = "Failed to Set Key in Redis (Key: '" + k + "')";
result.Result = false;
}
else
{
List<object> res = new List<object>
{
k
};
result.Data.Add(res);
result.Result = true;
}
}
}
catch (Exception ex)
{
LogToFile("Error executing query against Redis (Action: " + request.Action + ") - " + ex.Message, request.LogPath);
result.Error = "Error executing query against Redis (Action: " + request.Action + ") - " + ex.Message;
}
return result;
}

Uploading a file to folder

With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}

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 ?

Call WCF reference type variable

I am totally new to C#.
I have one service method
//actual method
public DataTable LoadDownLoadTablesData(string strBusinessUnit, string strExecutive, string strTableName, ref string strDate, string strTerritoryCode, string strUField1, string strUField2, string strUFeild3)
{
DataTable ds = new DataTable();
try
{
XontPDAServiceDAL vu = new XontPDAServiceDAL();
if (vu.validateExecutive(strBusinessUnit, strExecutive) == true)
{
DownloadFetchBLL wmd = new DownloadFetchBLL();
strDate = DateTime.Now.ToString();
ds = wmd.LoadDownLoadTableData(strBusinessUnit, strExecutive, strTableName, strTerritoryCode, strUField1, strUField2, strUFeild3);
}
else
{
throw new FaultException("Executive Not Active in the system.");
}
}
catch (FaultException) { }
catch (Exception ex)
{
throw new FaultException("Database Server is Not Responding." + ex.Message);
}
return ds;
}
//Converting datatable to String type
public string LoadDownLoadTablesDataJson(string strBusinessUnit, string strExecutive, string strTableName, ref string strDate, string strTerritoryCode, string strUField1, string strUField2, string strUFeild3)
{
DataTable dtDownloadJson = new DataTable();
dtDownloadJson = this.LoadDownLoadTablesData(strBusinessUnit, strExecutive, strTableName, ref strDate, strTerritoryCode, strUField1, strUField2, strUFeild3);
return this.ConverTableToJson(dtDownloadJson);
}
//Converting table to json
public String ConverTableToJson(DataTable dtDownloadJson)
{
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
// if (dtDownloadJson.Columns.Count > 0)
// {
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dtDownloadJson.TableName + "\" : [");
for (int i = 0; i < dtDownloadJson.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}else
{
return "0";
}
// }else{
// return "0";
// }
}
This LoadDownLoadTablesData() reference variable is there.
I have to pass call this LoadDownLoadTablesDataJson(....) from Android,
I called like this way;
// ksoap2 calling wcf
public SoapPrimitive soapPrimitiveData(String method_name1, String soap_action1, String NAMESPACE, String APPURL ,String tablename ) throws IOException,XmlPullParserException {
SoapPrimitive responses = null;
SoapObject request = new SoapObject(NAMESPACE, method_name1); // set up
request.addProperty("strBusinessUnit", "HEMA");
request.addProperty("strExec", "4515");
request.addProperty("strTableName", "RD.AlternativeProductHeader");
// after login we will get these fields value
request.addProperty("strDate", "2000-04-29");
request.addProperty("TerritoryCode", "KAND");
request.addProperty("strUField1", "");
request.addProperty("strUField2", "");
request.addProperty("strUField3", "");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap// envelope
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(APPURL);
httpTransport.debug = true;
try {
httpTransport.call(soap_action1, envelope);
responses = (SoapPrimitive) envelope.getResponse();
Log.w("log_tag", "#### 218 ####" + responses);
} catch (Exception e) {
e.printStackTrace();
}
return responses;
}
This always return "0". But when I run through dummy testing C# site, It return some result.
See
String da1 = "2000-04-29";
String s = client.LoadDownLoadTablesDataJson("HEMA", "4515", "RD.AlternativeProductHeader", ref da1, "KAND", "", "", "");
Label1.Text = s;
output is :
{"Table1" : [{"TableName" : "LoadDistributor","Description" : "Distributor ","MandatoryFlag" : "1","Status" : "","Priority" : "0"},{"TableName" : "LoadPrice","Description" : "Price ","MandatoryFlag" : "1","Status" : "","Priority" : "0"}]}
I have confuse how we want to pass reference type using Android?
Please help me..
Thanks in advance.
Should have give like this request.addProperty("strExecutive", "4515");
not request.addProperty("strExe", "4515");
I shoube be service argument name.Can't give different name
It looks like the property name in your andriod request doesn't match up with the parameter name on your .NET web service method: strExe != strExecutive.

Categories

Resources