Getting C# Method With jQuery in asp.net - javascript

I am using the code below to display an uploaded picture in asp.net . The Image name is change to a unique name and args.get_fileName retrieves the original name of the file instead of the new unique name.
How can I retrieve the new unique name:
protected void FileUploadComplete(object sender, EventArgs e)
{
var date = DateTime.Now.ToString("yyyy-MM-dd-hh_mm_ss");
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs("~/listingImages/" + date + filename);
}
Script:
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:100px;width:100px";
imgDisplay.src = img.src;
};
img.src = "/listingImages/" + args.get_fileName();
$('#bodyContent_Label1').html("/listingImages/" + args.get_fileName());
}

You should use password generating concept
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!#$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}

Related

Save text from javascript variable to .txt file

I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
How can I make variable "textt" accessible?
Here is a full code:
private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}
You might be looking for ContinueWith() which can be chained after ExecuteJavaScriptAsync().
In this example you need to use your JavaScript code as a function which returns anything (ex. textt). So I've created something like this:
var myScript = #"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:
var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});
this is just a suggestion of how it might work.

Need some help converting Js to C#

I need to convert this to c#, but I am not sure how to do it.
getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
(Basically, I would love to know what should I use instead of Object.keys)
This function iterates over some object's enumerable properties (Object.keys) and writes out the property values to a string - though without the keys and without any delimiters.
I don't know what _self.params refers to in this context as it isn't a JavaScript intrinsic nor have you provided its definition.
A direct translation to C# is not possible as C#/.NET do not use prototypes with enumerable properties, the closest analogue is to represent _self.params as a Dictionary<Object,String>:
public static String GetParamsAsStr(Dictionary<Object,String> p) {
if( p == null || p.Count == 0 ) return String.Empty;
StringBuilder sb = new StringBuilder();
foreach(Object key in p.Keys) sb.Append( p[key] );
return sb.ToString();
}
I am writing this as an answer to be able to place the whole thing...
This is the original JS code which sets the first parameter to make, later on, some API calls:
var Signer = function () {
this.apkId = getApkId();
this.apkSecret = getApkSecret();
this.servicio = "";
this.sessionToken = "";
this.timestamp = "";
this.requestId = "";
this.params = "";
var _self = this;
this.getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
this.getSignature = function () {
var baseString =
_self.apkSecret +
_self.servicio +
_self.sessionToken +
_self.timestamp +
_self.requestId +
_self.getParamsAsStr();
console.log("Signature pre hash:\n" + baseString);
baseString = baseString.toLowerCase();
return sha1(baseString);
}
}
And, so far, what I did in C# is the following:
public class Signer
{
public string appId = getApkId();
public string appSecret = getAppSecret();
public string servicio = "";
public string sessionToken = "";
public string timestamp = "";
public string requestId = "";
public string params = "";
//Here I have to write the getParamsAsStr()
private static string getApkId(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
private static string getAppSecret(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
}

Send files through AJAX using FormData to ASP.NET MVC

I have a simple model:
public class MyModel {
public string Description { get; set; }
public HttpPostedFileBase File {get; set; }
}
and my MVC action:
[HttpPost]
public ActionResult Upload(List<MyModel> data) {
// do soemthing
}
and finally JavaScript:
$("#chooseFile").on("change", function (){
var files = $(this).prop("files");
var array = [];
for(int i=0; i<files.length; i++) {
var obj = {};
obj.Description = "My custom description" + i;
obj.File = files[i];
array.push(obj);
}
var formData = new FormData();
formData.append("data", array);
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", "/test/Upload");
xmlHttpRequest.send(formData);
});
The problem is that data from the Upload action always has Count = 0 . Where is my mistake ?
In order bind to a collection of complex objects, the names (in the name/value pairs) must include indexers. Your script needs to add the names to FormData in the following format - '[0].Files', '[0].Description', '[1].Files', '[1].Description' etc
$("#chooseFile").on("change", function() {
var files = $(this).prop("files");
var formData = new FormData();
for(int i=0; i<files.length; i++) {
formData.append('[' + i + '].File', files[i]);
formData.append('[' + i + '].Description', 'My custom description' + i);
}
var xmlHttpRequest = new XMLHttpRequest();
....

Using ModelAndView object properties inside javascript

I am returning a list from my Controller as list to view and I am passing this list object to my javascript function like this
window.onload = function() {
showDirectory("$(S3DirectoryList)");
};
S3DirectoryList is the object that is returned from controller.
This is my model class
class Directory {
String folderName;
HashMap< String, String> objects;
List<Directory> dChild;
}
I want to use the folderName property of Directory in function.
Currently my javascript function is defined like this
function showDirectory( dirList) {
var markup="";
<c:forEach var="dir" items="dirList">
markup += ${dir.folderName} + "<br>";
</c:forEach>
document.getElementById("dispdir").innerHTML = markup;
}
I added some code to your Directory class. If you run it(I also added a Main method for testing purposes), you see it creates a list of directories and serializes this list as JSON. I added a constructor to make it easy to create some directories. I also added a getJSON method that serializes a directory. I added a getJSON(List directories) method to serialize a list of directories.
If you see to it this serialized list gets into your variable S3DirectoryList you can pass it to your javascript function as follows:
function showDirectory(dirList) {
var markup = "";
for(var i = 0; i < dirList.length; i++) {
markup += dirList[i].folderName + "<br />";
}
document.getElementById("dispdir").innerHTML = markup;
}
window.onload = function() {
showDirectory($(S3DirectoryList));
};
the Directory class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Directory{
String folderName;
HashMap<String, String> objects;
List<Directory> dChild;
public Directory(String folderName, String[] objects) {
this.folderName = folderName;
this.objects = new HashMap<String, String>();
for(int i = 0; i < objects.length; i = i + 2) {
this.objects.put(objects[i], objects[i + 1]);
}
this.dChild = new ArrayList<Directory>();
}
public void addChildDirectory(Directory childDirectory) {
if(this.dChild == null)
this.dChild = new ArrayList<Directory>();
this.dChild.add(childDirectory);
}
public String toJSON() {
StringBuilder b = new StringBuilder();
b.append("{");
b.append("'folderName': '").append(folderName == null ? "" : folderName).append("'");
b.append(",objects: {");
if(objects != null) {
Iterator<Map.Entry<String, String>> objectsIterator = objects.entrySet().iterator();
if(objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append("'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
while (objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append(",'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
}
b.append("}");
b.append(",'dChild': ");
b.append("[");
if(dChild != null) {
if(dChild.size() > 0)
b.append(dChild.get(0).toJSON());
for(int i = 1; i < dChild.size(); i++) {
b.append(",").append(dChild.get(i).toJSON());
}
}
b.append("]");
b.append("}");
return b.toString();
}
public static String getJSON(List<Directory> directories) {
StringBuilder b = new StringBuilder();
b.append("[");
if(directories.size() > 0)
b.append(directories.get(0).toJSON());
for(int i = 1; i < directories.size(); i++) {
b.append(",").append(directories.get(i).toJSON());
}
b.append("]");
return b.toString();
}
private static Directory generateDirectory(int seed) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 5; i++) {
directories.add(
new Directory(
"folderName_" + seed + "_" + i,
new String[]{"k_" + seed + "_" + i + "_1", "v_" + seed + "_" + i + "_1", "k_" + seed + "_" + i + "_2", "k_" + seed + "_" + i + "_2"}));
}
Directory directory_root = directories.get(0);
Directory directory_1_0 = directories.get(1);
Directory directory_1_1 = directories.get(2);
Directory directory_1_0_0 = directories.get(3);
Directory directory_1_0_1 = directories.get(4);
directory_root.addChildDirectory(directory_1_0);
directory_root.addChildDirectory(directory_1_1);
directory_1_0.addChildDirectory(directory_1_0_0);
directory_1_0.addChildDirectory(directory_1_0_1);
return directory_root;
}
public static void main(String[] args) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 2; i++) {
directories.add(generateDirectory(i));
}
System.out.println(toJSON(directories));
}
}

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources