I don't like to post such a general question, but I am not seeing a lot on the topic, so I was wondering if anyone has done something like this, and whether or not this is a good implementation to go with.
EDIT Added whole method
Here is the code
protected void gridViewAttachments_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
{
//if (e.DataColumn.FieldName == "AttachmentName" && e.CellValue.ToString().ToLower().Contains("://"))
// attachmentUrl = e.CellValue.ToString();
//if (e.DataColumn.FieldName == "AttachmentName" && !e.CellValue.ToString().ToLower().Contains("://"))
// attachmentUrl = "http://" + e.CellValue;
Uri targetUri;
if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
{
attachmentUrl = new Uri("http://" + e.CellValue);
}
if (e.DataColumn is DevExpress.Web.ASPxGridView.GridViewDataHyperLinkColumn)
{
if (attachmentUrl.ToString() == "")
{
DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink =
(e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
hyperlink.Target = "_blank";
hyperlink.NavigateUrl = ApplicationUrl + "/Attachment.ashx?key=" + hyperlink.Text;
hyperlink.Text = GetWords("GENERAL.VIEW_ATTACHMENT");
}
else
{
DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink = (e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
hyperlink.Target = "_blank";
hyperlink.NavigateUrl = attachmentUrl.ToString();
hyperlink.Text = "Go to URL";
}
}
}
Pretty basic, and it works. My question is this: Is checking if the string contains :// enough to check whether or not it is a url? The reason I have to check is it is pulling the data from table and some of the fields in the table are filenames (mydoc.docx) in which case I will do something else with them. Is there another more robust check I can do in C#?
You could use Uri.TryCreate instead to see if creation of the URL is successful:
Uri targetUri;
if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
{
//success
attachmentUrl = "http://" + e.CellValue;
}
Related
I am developing one application in web api and angularjs. I have file upload part. I am able to upload files and i am not storing files in webroot(i created folder called Uploads). My problem is i am not using any good naming convention to maintain uniqueness of files so there are chances of overriding files. I am new to angularjs so i refered below link. http://instinctcoder.com/angularjs-upload-multiple-files-to-asp-net-web-api/
This is my controller level code.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
var multipartFormDataStreamProvider = new CustomUploadMultipartFormProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
var fileName = "";
DateTime dt = DateTime.Now;
foreach (var key in multipartFormDataStreamProvider.Contents)
{
var a = key.Headers;
fileName = a.ContentDisposition.FileName;
break;
}
foreach (var key in multipartFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multipartFormDataStreamProvider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
In the above code I am trying to add date part to beginning of file name as below
string filenameNew = "App1" + DateTime.Now.ToString("yyyyMMddHHmmss");
fileName = filenameNew + a.ContentDisposition.FileName;
public CustomUploadMultipartFormProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
string startwith = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
return headers
.ContentDisposition
.FileName.TrimEnd('"').TrimStart('"').StartsWith("startwith").ToString();
}
return base.GetLocalFileName(headers);
}
This i tried but whatever the original file name that only comes. May I get some idea where can i append datepart to file while saving? Any help would be appreciated. Thank you.
I'm not sure what you're trying to do inside of the GetLocalFileName, this is pretty messed up.
First off, StartsWith returns a boolean (true or false) that indicates if the string starts with whatever you put in the parenthesis.
string str = "SIMPLE";
bool t = str.StartsWith("SIM"); // true
bool f = str.StartsWith("ZIM"); // false
The fact you're turning this bool back into a string and also passing the string "startsWith" into the method, means it will always return the string "false" (a bool value converted into a string) unless the real filename starts with "startsWith".
I think this is what you're looking for:
public override string GetLocalFileName(HttpContentHeaders headers)
{
string prefix = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
var filename = headers.ContentDisposition.FileName.Trim('"');
return prefix + filename;
}
return base.GetLocalFileName(headers);
}
My suggestion for you is to learn the basics of C# and .Net a bit more, maybe read a C# book or something.
I have simple code , wich get url path and redirect to this url:
private void Redirect(String path)
{
Uri validatedUri = null;
var result = Uri.TryCreate(HelpURL + path, UriKind.Absolute, out validatedUri);
if (result&&validatedUri!=null)
{
var wellFormed = Uri.IsWellFormedUriString(HelpURL + path, UriKind.Absolute);
if(wellFormed)
{
Response.Write("Redirect to: " + HelpURL + path);
Response.AddHeader("REFRESH", "1;URL=" + HelpURL + path);
}
else //error
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
else
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
Example of Url:http://web-server/SomeSystemindex.html. It is not valid address, but:
at my code result is true, wellFormed is true too!
How to validate url address?
P.S. HelpUrl+path=http://web-server/SomeSystemindex.html for this case. Where HelpUrl is 'http://web-server/SomeSystem', and path=index.html
P.P.S. I do as Martin says- create connection and check the status code.
HttpWebRequest req = WebRequest.Create(HelpURL + path) as HttpWebRequest;
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
var statusCode= ((HttpWebResponse)req.GetResponse()).StatusCode;
if (statusCode == HttpStatusCode.NotFound)
isValid = false;
else if (statusCode == HttpStatusCode.Gone)
isValid = false;
else
{
isValid = true;
}
As far as I know, the only way to determine whether an address is valid or not, is by opening a connection. If the connection lives, the address is valid. If not, the connection is not valid. There are some tricks to filter out bad URL's, but to know whether an adress is valid, you need to open a connection.
An example has already been posted on StackOverflow here
Or here:
URL url;
URL wrongUrl;
try {
url = new URL("http://google.com");
wrongUrl = new URL( "http://notavalidurlihope.com");
HttpURLConnection con = (HttpURLConnection ) url.openConnection();
System.out.println(con.getResponseCode());
HttpURLConnection con2 = (HttpURLConnection ) wrongUrl.openConnection();
System.out.println(con2.getResponseCode());
} catch (IOException e) {
System.out.println("Error connecting");
}
Note: Do disconnect afterwards
output:
200
Error connecting
This simple helper method uses regex to ensure that a website URL is in correct format. It will also fail if there is any white space (which is important).
The following URL's pass:
google.com
www.google.com
http://google.com
http://www.google.com
https://google.com/test/test
https://www.google.com/test
It fails on:
www.google.com/a bad path with white space/
Below is the helper method I created:
public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
Regex pattern = new Regex(#"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$");
Match match = pattern.Match(value);
if (match.Success == false) return false;
return true;
}
I am using below code on page load, but it gives me below error
"Object reference not set to an instance of an object."
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (("" + Request.QueryString["utm_source"] == "") && ("" + Request.QueryString["utm_medium"] == "") || ("" + Request.QueryString["utm_source"] == null) && ("" + Request.QueryString["utm_medium"] == null))
{
lblSource.Text = "Direct/Referral";
}
else
{
try
{
if (Request.UrlReferrer.OriginalString.ToString() != null)
{
string abc = Request.UrlReferrer.OriginalString.ToString();
string[] source = abc.Split('?');
string a1 = source[1];
a1 = a1.Substring(11);
string[] spl = a1.Split('&');
utm_source = spl[0];
string a2 = spl[1];
utm_medium = a2.Substring(11);
}
}
catch (Exception ex)
{
//Response.Write(ex);
lblSource.Text = "Direct/Referral";
}
}
//Response.Write(utm_source + " " + utm_medium);
lblSource.Text = utm_source + " " + utm_medium;
}
}
Yes, you are doing it correctly, but you need to put null checks first before using them. Following are some of codes that can be improved.
Use this if(Request.UrlReferrer!=null && !string.IsNullOrEmpty(Request.UrlReferrer.OriginalString)) instead of if (Request.UrlReferrer.OriginalString.ToString() != null) .
Use this Request.QueryString["utm_source"] != null instead of Request.QueryString["utm_source"] == "", because, it will try to covert it to string for comparison and that value is null , it will error as "Object reference not set to an instance of an object.".
To get exact querystring, from iFrame you can do it like this , instead of string manipulations.
protected void Page_Load(object sender, EventArgs e)
{
Uri parenturl = new Uri(Request.UrlReferrer.OriginalString);
string qyr = parenturl.Query;
NameValueCollection col = HttpUtility.ParseQueryString(qyr);
String kvalue = col["k"];
String mvalue = col["m"];
}
Assumption: The above code belongs to test1.aspx and i have one more page test2.aspx which has iFrame with src = test1.aspx . I have used http://localhost:52785/test2.aspx?k=1&m=2 url, so parent page has querystrings as k=1, m=2. See below screenshot, what i got.
You can try the following JavaScript, but only if the iframe and the site around come from the same domain (same origin policy).
var uri = document.getElementById("IdOfIframe").contentWindow.location.href;
Hi guys I am using Observable collection to store values in wpf datagrid but I want to delete duplicate rows automatically. Can anyone help me out. I have tried following way but didn't succeed. I am using MVVM.
My code :
public ObservableCollection<VLANSPropertyClass> vlan { get; set; }
vlan = new ObservableCollection<VLANSPropertyClass>();
void AddVlans()
{
if ((String.IsNullOrEmpty(VlanName)) ||
String.IsNullOrEmpty(VlanID) ||
String.IsNullOrEmpty(VlanIP1) ||
String.IsNullOrEmpty(VlanIP2) ||
String.IsNullOrEmpty(VlanIP3) ||
String.IsNullOrEmpty(VlanIP4) ||
String.IsNullOrEmpty(SelectedVlanPort))
{
MessageBox.Show("Please fill the empty fields", "Alert", MessageBoxButton.OK);
}
else
{
Console.WriteLine("Add vlan");
var serial = new VLANSPropertyClass();
serial.S_No = vlan.Count + 1;
serial.vname = VlanName;
serial.vid = VlanID;
serial.ip = VlanIP1 + "." + VlanIP2 + "." + VlanIP3 + "." + VlanIP4;
serial.mask = Vlanmask1 + "." + Vlanmask2 + "." + Vlanmask3 + "." + Vlanmask4;
serial.vports = SelectedVlanPort;
if (itemexists())
{
MessageBox.Show("Value already present");
}
else
{
vlan.Add(serial);
}
}
}
bool itemexists()
{
var item = new VLANSPropertyClass();
return
(item.vname == VlanName) &&
(item.ip == VlanIP1 + "." + VlanIP2 + "." + VlanIP3 + "." + VlanIP4) &&
(item.vname == VlanName) &&
(item.vports == SelectedVlanPort);
}
The above methods is adding rows but it's not deleting duplicate rows automatically .Any help would be highly appreciable.
You can use the LinQ Enumerable.Distinct<TSource> Method to remove duplicate items from a collection. Try something like this:
vlan = GetSomeData(); // Fill with data however you want
vlan = new ObservableCollection<VLANSPropertyClass>(vlan.Distinct());
This could even be shortened to:
vlan = new ObservableCollection<VLANSPropertyClass>(GetSomeData().Distinct());
This will only work to remove exact duplicates objects though... that is, objects that share the same reference. If you just want to remove objects that have the same property values, then you could use the overloaded Enumerable.Distinct<TSource> Method which takes an IEqualityComparer<T> parameter. Of course, you'd need to implement the IEqualityComparer<T> interface to make that work correctly.
Sorry my comment...I didn't see correctly your code.
Your problem is in your boolitemexists.
Try this:
if (vlan.FirstOrDefault( YOUR_CONDITIONS) ==null)
return false;
else return true;
YOUR_CONDITIONS I think must be something like:
x=>x.vname == serial.name && .....
Your boolexistsitem should receive the serial as parameter.
Regards,
=========NEW EDIT
bool itemexists(VLANSPropertyClass serial){
if(vlan.FirstOrDefault(x=>x.vname ==serial.vname && serial.ip==x.ip && x.vports==serial.vports) == null)
return false;
else return true;
}
Let's assume an aspx page gets multiple querystrings, for example books.aspx?author=Arthor&level=4&year=2004.
I'd like to create a button that clears specific querystring.
For example when clearAuthorBtn is clicked, user should be redirected to books.aspx?level=4&year=2004
How can I make it?
Thank you very much.
ASP.NET, C# something like this pseudo-code should work in your button event handler:
foreach (var key in Request.QueryString)
{
string url = "books.aspx?";
if (key != "author")
{
url = url + Server.UrlEncode(key) + "=" + Server.UrlEncode(Request.QueryString[key]) + "&";
}
Response.Redirect(url);
}
Here is a method that may help. I have not tested this particular implementation, but something like it should suffice (and be fairly robust).
public static string GetQueryStringWithoutKey(HttpRequest request, string keyToRemove) {
// Assert keyToRemove is not null.
if (keyToRemove == null) {
throw new ArgumentNullException("keyToRemove");
}
// If the QueryString has no data, simply return an empty string.
if (request.QueryString.AllKeys.Length == 0) {
return string.Empty;
}
// Reconstruct the QueryString with everything except the existing key/value pair.
StringBuilder queryStringWithoutKey = new StringBuilder();
for (int i = 0; i < request.QueryString.AllKeys.Length; i++) {
// Only append data that is not the given key/value pair.
if (request.QueryString.AllKeys[i] != null &&
request.QueryString.AllKeys[i].ToLower() != keyToRemove.ToLower()) {
queryStringWithoutKey.Append(request.QueryString.AllKeys[i]);
queryStringWithoutKey.Append("=");
queryStringWithoutKey.Append(request.QueryString[i]);
queryStringWithoutKey.Append("&");
}
}
// We might have had a key, but if the only key was Message, then there is no
// data to return for the QueryString.
if (queryStringWithoutKey.Length == 0) {
return string.Empty;
}
// Remove trailing ampersand.
return queryStringWithoutKey.ToString().TrimEnd('&');
}
You can call the above method like this (note that I use HttpContext.Current in case you want to call this outside of an Page or UserControl):
HttpRequest request = HttpContext.Current.Request;
string url = request.ServerVariables["PATH_INFO"];
string queryString = GetQueryStringWithoutKey(request, "author");
if (!string.IsNullOrEmpty(queryString) {
url += "?" + queryString;
}
HttpContext.Current.Response.Redirect(url);