Replace double quotes with single quotes - double

I would like to change "1964" to '1964'
I have tried all combination but no success
string rowString = "1964";
var myString = "1964";
var myStrin = Regex.Replace(myString, #"[\""]", "'", RegexOptions.IgnoreCase);
string y = rowString.Trim('"');
string yy = rowString.Replace("\"", String.Empty);
var yvc = rowString.Replace("\"", String.Empty);
rowString = rowString.Replace("\"", "'");
rowString.Trim('"', '\'', ' ');
rowString = rowString.Replace('"', ' ').Trim();
var somestring = rowString.Replace('"', ' ').Trim();
rowString = rowString.Replace("'", "''");
string strgs = rowString.Replace("'", "''");
string strgg = rowString.Replace("\"", "'");
string strgod = rowString.Replace("\"", "'");
string strgodd = rowString.Replace("\"", "").Replace("'", "");

just do var newString= "'" +myString + "'"

Related

Is there a way to replace multiple keywords in a string and wrapping them with their own keyword?

Say I have a string:
typed = "need replace this ap"
str = "hello I need to replace this asap"
so the end result I want would be this:
newStr = "hello I <bold>need</bold> to <bold>replace</bold> <bold>this</bold> as<bold>ap</bold>"
please don't mind the weird syntax.
I wonder if the order would matter, for example:
typed = "applicable app"
str = "the app is very applicable in many applications"
The end result I wish should be:
newStr = "the <bold>app</bold> is very <bold>applicable</bold> in many <bold>app</bold>lications"
right? is this possible?
Hey,If You can ignore the weird HTML syntax here,
Then I have wrote a solution for you,
Paste this code in dart pad here
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2;
}
return ans;
}
void main() {
String typed = "need replace this ap";
var str = "hello I need to replace this asap";
String answer = removeDuplicates(typed, str);
print(answer);
}
Here, I have made a method removeDuplicates() to simplify your work, You just have to pass those string in your method, and then it will return you the desired answer string by removing the duplicates, with a new string.
UPDATED CODE (TO SHOW HTML CODE):
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
print(m);
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
ans = ans + " " + temp2;
} else {
ans = ans +
" " +
temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
temp2 = "";
} else {
ans = ans + " " + temp2;
temp2 = "";
}
return ans;
}
void main() {
var typed = "applicable app";
var str = "the app is very applicable in many applications";
String answer = removeDuplicates(typed, str);
print(answer);
}
UPDATE 2 (ALL THANKS TO PSKINK FOR THE str.replaceAllMapped APPROACH)
replaceWithBoldIfExists(String typed, String str) {
var n = typed.length;
List<String> searchList = new List<String>();
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
searchList.add(temp);
temp = "";
} else {
temp = temp + typed[i];
}
}
searchList.add(temp);
String pat = searchList.join('|');
final pattern = RegExp(pat);
final replaced =
str.replaceAllMapped(pattern, (m) => '<bold>${m.group(0)}</bold>');
return replaced;
}
void main() {
var typed = "need replace this ap";
var str = "hello I need to replace this asap";
print(replaceWithBoldIfExists(typed, str));
}

azure REST API communication

I'm currently trying retrieve list share available in my Azure account from salesforce. I'm trying to implement the example from below sample code:
https://learn.microsoft.com/en-us/rest/api/storageservices/list-shares#samplerequestandresponse
//private key: access key of my account
string storageKey =private key;
string storageName = 'accountName';
Datetime dt = Datetime.now();
string formattedDate = dt.formatGMT('EEE, dd MMM yyyy HH:mm:ss')+ ' GMT';
system.debug('formattedDate--'+formattedDate);
string CanonicalizedHeaders = 'x-ms-date:'+formattedDate+'\nx-ms-version:2016-05-31';
string CanonicalizedResource = '/' + storageName + '/\ncomp:list';
string StringToSign = 'GET\n\n\n\n\n\n\n\n\n\n\n\n' + CanonicalizedHeaders+'\n'+CanonicalizedResource;
system.debug('StringToSign--'+StringToSign);
Blob temp = EncodingUtil.base64Decode(storageKey);
Blob hmac = Crypto.generateMac('HmacSHA256',Blob.valueOf(StringToSign),temp ); //StringToSign
system.debug('oo-'+EncodingUtil.base64Encode(hmac));
HttpRequest req = new HttpRequest();
req.setMethod('GET');
//req.setHeader('content-type', 'application/xml');
req.setHeader('x-ms-version','2016-05-31' );
req.setHeader('x-ms-date', formattedDate);
string signature = EncodingUtil.base64Encode(hmac);
string authHeader = 'SharedKey salesforcestrongaccount'+':'+signature;
req.setHeader('Authorization',authHeader);
req.setEndpoint('https://<accountName>.file.core.windows.net/?comp=list');
Http http = new Http();
HTTPResponse res;
res = http.send(req);
System.debug(LoggingLevel.INFO, 'http.send result status: ' + res.getStatus());
Any help?
As Gaurav Mantri says, there are something wrong with your stringToSign. So you will get this error.
The right Shared Key Authentication is like this:
StringToSign = VERB + "\n" +
Content-Encoding + "\n" +
Content-Language + "\n" +
Content-Length + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
If-Modified-Since + "\n" +
If-Match + "\n" +
If-None-Match + "\n" +
If-Unmodified-Since + "\n" +
Range + "\n" +
CanonicalizedHeaders +
CanonicalizedResource;
Here I create a test demo, you could refer to it.
List share:
string storageAccount = "storage account";
string accessKey = "accountkey";
string resourcePath = "?comp=list";
string uri = #"https://" + storageAccount + ".file.core.windows.net/" + resourcePath;
// Web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
request.Headers["x-ms-version"] = "2015-02-21";
String stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + request.Headers["x-ms-date"] + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + storageAccount + "/" + "\ncomp:list"; // resources
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
string strAuthorization = "SharedKey " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));
request.Headers["Authorization"] = strAuthorization;
Task<WebResponse> response = request.GetResponseAsync();
HttpWebResponse responseresult = (HttpWebResponse)response.Result;
using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
{
string jsonData = r.ReadToEnd();
Console.WriteLine(jsonData);
}
Result:
Java:
private static final String account = "accountname";
private static final String key = "Key";
public static void main(String args[]) throws Exception {
// String urlString = "http://" + account + ".file.core.windows.net/sampleshare/name.txt";
String urlString = "https://" + account + ".file.core.windows.net/?comp=list";
HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
getFileRequest(connection, account, key);
connection.connect();
System.out.println("Response message : " + connection.getResponseMessage());
System.out.println("Response code : " + connection.getResponseCode());
BufferedReader br = null;
if (connection.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
public static void getFileRequest(HttpURLConnection request, String account, String key) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
String stringToSign = "GET\n" + "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + date + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + account + request.getURL().getPath() + "\ncomp:list"; // resources
System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
request.setRequestMethod("GET");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2015-02-21");
request.setRequestProperty("Authorization", auth);
}
private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
String auth = "SharedKey " + account + ":" + authKey;
return auth;
}

'DATE' cannot hold values of type 'INTEGER'

I've set up an SQL database and used 'Date' as my column header which obviously has its own format as opposed to integer or char etc. However when I put in a date such as 2/11/2016 it gives me the error message - 'DATE' cannot hold values of type 'INTEGER'. Does anyone know what code I should be using? Here's my jsp below. All goes into DB when I remove all reference to date.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(" + tableNum + "," + "'" + firstName + "'" + "," + "'" + lastName + "'" + "," + "'" + Address + "'" + "," + Phone + "," + date + "," + People +")";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>

Cursor not returning any value,it is showing error?

Am calling readPlaceName from TourGuideController, and passing the string in method readPlaceName(Placename), the cursor is showing null pointer exeception, not showing any values,Can any give solution for this error?
TourGuideController.java
public Cursor readPlaceName(String place_name){
String sql = "SELECT * FROM " + TourGuideDatabasehandler.VISTING_INBETWEEN_PLACES +
" WHERE "+ TourGuideDatabasehandler.PLACE_NAME + " = '" + place_name+"'";
Log.e("","Sql "+sql);
Cursor v = database.rawQuery(sql,null);
Log.e("v","Cursor v : "+v.toString());
return v;
}
MainActivity.java
protected void onPostExecute(Void result) {
super.onPostExecute(result);
int time = t_time;
TourGuideController dbcon = new TourGuideController(ourcontext);
System.out.println("dbcon"+dbcon+"temp_dbcon"+dbcon);
Log.e("OPEN","DB OPEN "+dbcon);
String place = "Juhu Beach";
Cursor cursors = dbcon.readPlaceName(place);
Log.e("dpopen", "cursor"+cursors);
Log.e("Updating cursor and cursor", DatabaseUtils.dumpCursorToString(cursors));
Integer wait_time = null;
while(cursors.moveToNext())
{
wait_time = Integer.parseInt(cursors.getString(8));
}
cursors.close();
String google_distance_time = "5";
Integer google_time = null;
google_time = Integer.parseInt(google_distance_time);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time1 = formatter.parseLocalTime(start_time);
System.out.println("wait_time"+wait_time);
int pred_time = (wait_time) + (google_time);
int get_total_time = (time)-(pred_time);
total_time = String.valueOf(get_total_time);
int addTimeMin = pred_time;
time1 = time1.plusMinutes(addTimeMin);
prediction_time = String.valueOf(time1);
dbcon.updateDateTime(place, start_date, start_time,google_distance_time,prediction_time,total_time);
Cursor cursor2 = dbcon.readPlaceName(place);
Log.e("Updating time and date", DatabaseUtils.dumpCursorToString(cursor2));
}
}}

excel data uploading is not working in sql database

This is pradeep
This is the code of the excel uploading to sql database
protected void btnupload_Click ( object sender, EventArgs e )
{
//string name = ddloutlet.SelectedValue.ToString ();
//cal
try
{
System.IO.FileInfo file = new System.IO.FileInfo(fileupload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length), file.Extension.Length);
fname = fname + DateTime.Now.ToString("_ddMMyyyy_HHmmss") + file.Extension;
fileupload1.PostedFile.SaveAs(Server.MapPath("locations/") + fname);
string filexetion = file.Extension;
if ( filexetion == ".xlsx" )
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
}
else if ( filexetion == ".xls" )
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes; \"";
}
OleDbConnection connection = new OleDbConnection(excelConnectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
SqlConnection conn = new SqlConnection(strconnection);
conn.Open();
try
{
if (dr.Read() == true)
{
while (dr.Read())
{
string locationname = dr["Location Name"].ToString();
string status = dr["Status"].ToString();
if (locationname != "" && status != "")
{
string query = " select locationname from tbllocations where locationname='" + locationname + "' and outletid='" + Session["outlet_id"].ToString() + "'";
// conn.Open();
SqlCommand cmdquery = new SqlCommand(query, conn);
SqlDataReader drreader;
drreader = cmdquery.ExecuteReader();
if (drreader.Read())
{
c = true;
ssss = ssss + locationname + ",";
// ss = ssss.Split(',');
}
else
{
drreader.Close();
string qryprduct = "insert into tbllocations(locationname,status,outletid,cityid)values('" + locationname + "','" + status + "','" + Session["outlet_id"].ToString() + "','" + Session["cityid"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(qryprduct, conn);
conn.Close();
conn.Open();
cmd1.ExecuteNonQuery();
lblerror1.Visible = true;
lblerror1.Text = "Locations uploaded Sucess";
//conn.Close();
}
drreader.Close();
}
}
// connection.Close (); conn.Close ();
}
else
{
lblerror1.Text = "There is a empty excel sheet file,plz check";
lblerror1.Visible = true;
}
}
catch (Exception ex)
{
lblerror1.Visible = true;
lblerror1.Text = "Plz check the excel file formate";
}
finally
{
connection.Close(); conn.Close();
bind();
if (c == true)
{
lblerror1.Visible = true;
lblerror1.Text = "In excel this loactions are already exist. Please check,";
//for (int i = 0; i < ss.Length; i++)
//{
lblerror3.Visible = true;
lblerror3.Text = ssss;
//}
}
}
}
catch
{
}
}
The above code uploading is working but in excel 1st record is not uploading ,please tell me the what is the problem and give me suggestion please.
excel data is
Location Name Status
test1 1
test2 1
test3 1
test4 0
test5 1
test6 0
test7 1
test8 0
test9 1
test10 1
Thanks
Pradeep
You need to remove the
if (dr.Read() == true)
because it is immediately followed by a
while (dr.Read())
Each of these will read a record and the first one will skip the first row of the file