|
I am working on .NET 4.0 MVC project. I am trying to Ajax post a piece of data from my KO model. That data is a string in following XML format.
<SearchCriteria><Criteria SearchOn="Name" SearchValue="test 3" /></SearchCriteria>
I am trying to post it like this.
$.ajax({
url: destUrl,
data: ko.toJSON(DataToPost()),
type: "POST",
success: function (result) {
}
},
error: function (request, textStatus, errorThrown) {
alert(request.statusText);
}
});
Here you will notice the data being sent is "ko.toJSON(DataToPost())". DataToPost() returns the XML string contained in my KO model data member DataToPost. ko.toJSON() is used to convert the KO model data in JSON.
This throws a runtime exception which is normally thrown when we post anything containing javascript or html tags. This is a security feature by .NET. Following is the exception.
A potentially dangerous Request.Form value was detected from the client.
<SearchCriteria><Criteria SearchOn="...est 3\" /></SearchCriteria>
I faced similar situation sometimes back (though I was not using KO that time and it was normal post i.e. non Ajax). I overcame the problem that time by using javascript escape() but this time it failed. I used it as follows
$.ajax({
url: destUrl,
data: ko.toJSON(escape(SearchCriteria())),
type: "POST",
success: function (result) {
}
},
error: function (request, textStatus, errorThrown) {
alert(request.statusText);
}
});
Other popular fix is to disable this security either at page level or at application level. It could be done as follows.
Page level.
<%@ Page validateRequest="false" %>
Application level.
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
But doing away with this security is not good. I don't think it will be a wise move. Right now I don't know what to do. Need suggestions.
Thanks in advance!
|
|
|
|
|
I realized that it is difficult to serialize an XML formatted string hence instead of XML formatted string I decided to post List of Key value pair instead. This approach is working fine.
|
|
|
|
|
Hi
How can I navigate by one navigationbar image with different button home , aboat. contact in .NET ?
I have MasterPage and sitemap to navigate on my website.
muehai
tigrina lexikon ትግርኛ መዝገብ ቃላት seglelet.com
.NET and C# is the most interested thing to me.
I have Tigrina Lexikon which I work att http://www.seglelet.com company at the moment!
|
|
|
|
|
I have an XML and an XSL for it.
I want to know how can I display this data when I open an HTML page.
Is there any way I can include this xml in html, so that i can view this data?
I googled and also searched in The Code Project, i could only find the solutions using javascripts and asp. I also tried out with many samples which did not work out.
I want to use only XML, XSL and HTML to display the data.
Please help me. Thanks in advance.
|
|
|
|
|
|
I am using knockout (KO) in my MVC project. I create an MVC model (for a grid) on server and pass it to the view. On the view it is serialized and converted into a KO model (using ko.mapping) which in turn is used for binding. That binding is then used in HTML for grid creation.
This is how my MVC grid model looks like which in turn gets converted to corresponding KO model by ko.mapping:
public class GridModel
{
public GridBodyModel GridBodyModel { get; set; }
public GridContext GridContext { get; set; }
public GridHeaderModel GridHeader { get; set; }
}
public class GridBodyModel
{
public IList<GridRowModel> Rows { get; set; }
}
public class GridContext
{
public int TotalPages{ get; set; }
}
public class GridHeaderModel
{
public IList<GridHeaderCellModel> Cells { get; set; }
}
As it is clear the main model class GridModel is made of following classes which are present as properties:
GridBodyModel: Has list of rows to be rendered in the grid body.
GridContext: Has total number of pages as a property. It has other properties as well but that is out of scope of this discussion.
GridHeaderModel: Has a list of cells that has to be displayed in header of the grid.
Then I have this script that will execute on fresh page load.
$(document).ready(function () {
ko.applyBindings(Global_GridKOModel, document.getElementById("gridMainContainer"));
});
Global_GridKOModel = ko.mapping.fromJS (<%= DataFormatter.SerializeToJson(Model) %>);
Global_GridKOModel is global javascript variable.
Model is the MVC grid model coming from server.
A user can perform further search on the page again. I handle this by posting new search criteria via Ajax. On this post a new MVC model is created and is sent back as Ajax response. This new MVC Model is then simply used to update Global_GridKOModel using ko.mapping which in turn refreshes the grid (with new data) that was constructed earlier on fresh page load. This is how I am doing it.
$.ajax({
url: destUrl,
data: dataToSend
success: function (result) {
ko.mapping.fromJS(result, Global_GridKOModel);
},
error: function (request, textStatus, errorThrown) {
alert(request.statusText);
}
});
Everything is working fine except in the following scenario.
An Ajax request is made for which no result is returned i.e. GridBodyModel and GridHeaderModel is null in the model GridModel. That time grid rightly shows that no record has been found. This is correct. This happens by the following HTML binding.
<!--
<div data-bind="ifnot: GridContext.GridPager.TotalPages() > 0">
No record(s) were found.
</div>
<!--
<div data-bind="if: GridContext.TotalPages() > 0">
Grid construction happens here
</div>
Now after this if another Ajax request is made but this time records are returned (I have checked the response with firebug and it is confirmed that records are indeed returned). This time grid construction happens wherein various observable arrays are accessed. For example, to construct pager for the grid following is a piece of HTML binding I wrote.
<td data-bind="attr:{colspan: GridHeader.Cells().length }">
This time KO throws following error which can be seen in firebug.
Unable to parse bindings.
Message: TypeError: GridHeader.Cells is not a function;
Bindings value: attr:{colspan: GridHeader.Cells().length }
It work fine so long there are records being returned but it breaks after no record is returned as explained above. Please note GridHeader was null in earlier response when no records were returned. I smell something fishy in ko.mapping. I think there is some problem while mapping observable array.
So what is it that I am not doing right? Anyone please?
Please feel free to ask for clarification if I have not mentioned things clearly.
Thanks in advance.
|
|
|
|
|
I figured it out last night. Actually this was very basic mistake that I was making. I was trying to access an array after setting it to null. I will explain it how.
When result were returned that time GridHeaderModel and the IList Cells in it were defined i.e. were not null. That time ko.mapping was able to convert the model and create the model and arrary inside it. But when any ajax request were made wherein noo result was returned and GridHeaderModel was null, obviously the IList Cells was null too. That time ko.mapping did the same, the KO model that it updated, set GridHeaderModel to null too and the observable array Cells inside was no present which is as good as null. Now when I made another ajax request with some records returned, the ko.mapping tried to update the observable array Cells which did not exist (or was set to null) in KO model on the client, it failed. If instead of ajax it were fresh page load everything would have worked. So the solution is not to return any enumeration (those that will get converted to observable array) uninitialized to the client for KO model update. Hence when no record was to be returned I made sure that GridHeaderModel is not null and also made sure that the IList Cells is initialized though it did not contained any element. This fixed the problem.
This problem could be explaied with following example.
public class Demo
{
public IList<string> DemoArray;
}
public class DemoUser
{
public void UseDemo()
{
var demoInstance = new Demo();
demoInstance.DemoArray.Add("First Element");
}
}
Here in the UseDemo() method we have initialized the class instance Demo but the IList DemoArray remains un-initialized. So when we try to access it runtime exception will be thrown. This is what was happening in my case. In first ajax response I was setting the observable array to null i.e. un-initializing it and then in next ajax response I was trying to access it.
modified 19-May-12 2:26am.
|
|
|
|
|
I have the excel file (Insert.xls) and i want to bind the data from it.
I wanna bind data with various Textboxes for each excel column.
How can i read it ?
please suggest me or please pay the sample codes for it.
|
|
|
|
|
Hey they are 2 ways which you can achieve this. You can get the cell range and store it in an array and then read the values from the array like so :
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
TextBox.Text = strArray[0].ToString();
}
}
or you could use OleDb like so assuming you have a sheet in the excel file called MyObject :
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con);
DataTable dt = new DataTable();
da.Fill(dt);
Hope this helps
|
|
|
|
|
Another way is to save the excel file in csv(tab seperated) format and use a streamreader to read the file. Then declare an array and split the reader into the array, if you need a code sample let me know and il gladly provide it.
|
|
|
|
|
Is there any specific harm or drawback if we use Session state in SharePoint 2010 ?
Actually we have a scenario in which we have to perceive the 100 rows (with seven column in each row) in a DataTable and perceive its values during the page refresh call that is being made on close of the SharePoint Modal Dialog box .
Actually we have to insert the rows to the datatable of parent page by opening a Modal Popup without submitting the data to the database .
Does storing the datatable with 100 rows in VIEWSTATE will be an alternate solution ,if Session state is not recommended ? Or we can go ahead with Session state ?
name :atharfaridi
from :pune university
currently residing in mumbai
|
|
|
|
|
I need to display a message box in my asp.net application with 3 buttons yes no cancel. I need to detect which button has been clicked and perform some actions depending on the button clicked.
I've tried the following code:
Dim result1 As Forms.DialogResult = System.Windows.Forms.MessageBox.Show("Message1", System.Windows.Forms.MessageBoxButtons.YesNoCancel, Forms.MessageBoxIcon.Warning, Forms.MessageBoxDefaultButton.Button1, Forms.MessageBoxOptions.DefaultDesktopOnly, False)
If result1 = Forms.DialogResult.Yes Then '(System.Windows.Forms.DialogResult.No)
//code
ElseIf result1 = Forms.DialogResult.No Then
//code
Else
Exit Sub
End If
it works only when the application is on my local machine.
When I tried to access the application from aserver, the message box is displayed on the server, not on the client browser.
Any help will be appreciated.
Cheers
|
|
|
|
|
|
Hi
We have a dynamic website where we are sending emails to users (like reminder emails like linkedin or facebook does. For example , if user has not verified his email id, then we send them verification emails ) . Now these emails are successfully delivered to users who are using hotmail, yahoo and Outlook but it is going in spam in case of Gmail. I am not sure why it is going in spam.
We are like sending 5 emails in 1 second and currently using our own IP . Our ip is not in blacklisted list anywhere . And also as I am saying its going well in all other email clients except gmail.
We would like to send emails by Amazon SES but the ip which they had provided us was blacklisted and some of the emails were not delivered. So we turned off that thing until we get a clean IP and started using ours.
Our website is live and we would like to know the solution asap. Also , sometimes the email goes well in gmail if we are sending 1 email at a time after longer duration but when we are sending these reminder emails , then its going into SPAM.
Please help.
I have attached the file where we are calling sendemails function which infact is send function to send emails. There are 2 send email function , one is for sending through amazon SES and other is through normal asp.net email function. Do you also want the text which we are sending? It is long text with 3-4 click here outbound links but professional and corporate text.
I am looking for help asap.
private void SendEmails(string UserEmail, string from, string subject, string mail_content)
{
TimeSpan timeSpanForDelay = new TimeSpan(0, 0, 0, 0, 200);
System.Threading.Thread.Sleep(timeSpanForDelay);
Send(UserEmail, from, subject, mail_content);
}
public void Send(string MessageTo_EmailID, string MessageFrom_EmailID, string Subject, string MailBody)
{
try
{
string head = string.Empty;
string foot = string.Empty;
MessageFrom_EmailID = WebConfigurationManager.AppSettings["FromEmail"].ToString();
bool sendEmailFromAmazone = false;
try
{
PostBuyerOffer objbuyer = new PostBuyerOffer();
DataTable dtParam = objbuyer.FungetParameterDetail("Email Function for Sending Email");
if (dtParam.Rows.Count > 0)
{
if (dtParam.Rows[0]["Pvalue"].ToString().ToLower() == "amazon ses")
sendEmailFromAmazone = true;
}
}
catch { }
DataTable dt = new DataTable();
if (HttpContext.Current.Session["AdminRecords"] == null)
{
dt = objMem.GetAdminDetails();
HttpContext.Current.Session["AdminRecords"] = dt;
}
else
dt = (DataTable)HttpContext.Current.Session["AdminRecords"];
if (dt.Rows.Count > 0)
{
if (sendEmailFromAmazone)
{
try
{
string smtpServer = dt.Rows[0]["awsMailServer"].ToString();
string userName = dt.Rows[0]["awsAccessKey"].ToString();
string password = dt.Rows[0]["awsSecretAccessKey"].ToString();
List listColl = new List();
listColl.Add(MessageTo_EmailID);
SendEmailRequest mailObj = new SendEmailRequest();
Destination destinationObj = new Destination(listColl);
mailObj.Source = MessageFrom_EmailID;
mailObj.ReturnPath = MessageFrom_EmailID;
mailObj.Destination = destinationObj;
Amazon.SimpleEmail.Model.Content emailSubjectObj = new Amazon.SimpleEmail.Model.Content(Subject);
Amazon.SimpleEmail.Model.Content emailBodyContentObj = new Amazon.SimpleEmail.Model.Content(MailBody);
Amazon.SimpleEmail.Model.Body emailBodyObj = new Body();
emailBodyObj.Html = emailBodyContentObj;
Message emailMessageObj = new Message(emailSubjectObj, emailBodyObj);
mailObj.Message = emailMessageObj;
AmazonSimpleEmailServiceConfig amConfig = new AmazonSimpleEmailServiceConfig();
amConfig.UseSecureStringForAwsSecretKey = false;
amConfig.SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256;
Amazon.SimpleEmail.AmazonSimpleEmailServiceClient client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(userName, password, amConfig);
SendEmailResponse response = client.SendEmail(mailObj);
SendEmailResult result = response.SendEmailResult;
string s = result.ToString();
}
catch (Exception ex)
{
}
}
else
{
string smtpServer = dt.Rows[0]["SMTPServer"].ToString();
string userName = dt.Rows[0]["SMTPUser"].ToString();
string password = dt.Rows[0]["SMTPPwd"].ToString();
int cdoBasic = 1;
int cdoSendUsingPort = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"]);
string mailBody = MailBody;
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(head + mailBody + foot);
mailBody = System.Text.ASCIIEncoding.ASCII.GetString(b);
SmtpClient emailClient;
NetworkCredential SMTPUserInfo;
MailMessage msg = new MailMessage(MessageFrom_EmailID, MessageTo_EmailID, Subject, mailBody);
msg.Body = mailBody;
msg.Priority = MailPriority.Normal;
msg.IsBodyHtml = true;
if (userName != "" && password != "")
{
emailClient = new SmtpClient(smtpServer);
emailClient.Port = cdoSendUsingPort;
SMTPUserInfo = new NetworkCredential(userName, password);
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = SMTPUserInfo;
}
else
{
emailClient = new SmtpClient(smtpServer);
emailClient.Port = cdoSendUsingPort;
emailClient.UseDefaultCredentials = false;
}
try
{
emailClient.Send(msg);
}
catch (Exception ex)
{
}
}
}
HttpContext.Current.Session.Remove("AdminRecords");
}
catch { }
}
|
|
|
|
|
The sender of your emails is MessageFrom_EmailID . Is your server's IP listed as a mail server for the domain given in that variable?
|
|
|
|
|
Hi there,
at the beginning I must admit that I am not good at PHP. I made a few websites in HTML but now I don't know what happened and what to do with it.
I wanted to change a few things at http://www.tips2.pl/ which is made in PHP. Everything worked fine till I placed a ".htaccess" file on the server. I wanted to disable an URL without "www.": http://tips2.pl and left only http://www.tips2.pl/.
I transfered a ".htaccess" file from my another project. It looks like this:
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule . http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . %1 [R=301,NE,L]
Since this moment I can see only main page, all the subpages are not found.
I think it may be the fault of line:
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
How can I fix this?
Thanks in advance.
kukula
|
|
|
|
|
Can the web-server be configured not to accept requests without "www"? When I remember correctly, I configured such a thing a few years ago for a website on IIS. Then you won't need the php code.
|
|
|
|
|
I know this is rather general, but I want to build a sort of web crawler. Rather than taking apart websites, I want it to search the internet for all instances of something. A license plate number, or full name, or something of the sort.
Does anyone have experience with this? I have given it some thought and I realize I could certainly give it a list of sites to crawl (Google, Bing, etc...), or I could have it run through IP addresses sequentially.
Thoughts?
|
|
|
|
|
First of all: become realistic.
When you enter a search term in Google, Bing, etc, what do they do then? Do you think they tell their web crawlers to start searching the web just now? No, not at all. They already downloaded "all" of internet and built large databases. Then they query those local databases.
And now just look at the sizes: how many bytes do all the pages of the internet have? How long will it take to download them? What will your internet provider tell you when you try...
|
|
|
|
|
I need to format the date on my asp.net application based on my regional settings.
If I change the regional settings, the date format should automatically changed in my application.
Any help will be highly appreciated.
Thanks
Berba
|
|
|
|
|
Take a look at some of these links[^] for suggestions.
Binding 100,000 items to a list box can be just silly regardless of what pattern you are following. Jeremy Likness
|
|
|
|
|
|
I have the table(tblCompany) which have the fields(ID,CompanyName,Address,PhoneNumber,Email)etc..
There is a data entry man(Role=marketer) to insert the company.
I don't want to publish (new company) directly to the website and I(Role=Admin) wanna check again .
If i approve the (new Company) , then publish to the users(Role=Public and Role= Annonymous).
How can I write the code for this problem?
Please , suggest to me my all dear.....
|
|
|
|
|
Add a status field to the tblCompany which could be used to filter the data which is displayed on the website.
For example:
0 - Company is initially created
1 - Appproved
2 - Marked as delete
Based on role you can filter what is displayed.
|
|
|
|
|
thanks dear brother.....that's work
|
|
|
|
|