ASP.NET MVC PartialView gives an error some times? - asp.net-mvc

I use partialview like
<td style="vertical-align: top;">#Html.Action("_HavaDurumuPartial")
And It is working on server now. But sometimes It gives error. Erros is below:
This error not occur allways.
I cant find any reason for this problem.And I cant understand why does it sometimes give this error.
If it is neccesary, I write the content of partialview and controller action.
action
public ActionResult _HavaDurumuPartial(string il)
{
il = "Izmir";
HttpWebRequest GoogleRequest;
HttpWebResponse GoogleResponse = null;
XmlDocument GoogleXMLdoc = null;
try
{
GoogleRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?weather=" + il + "&hl=tr&ie=utf-8&oe=utf-8");
GoogleResponse = (HttpWebResponse)GoogleRequest.GetResponse();
GoogleXMLdoc = new XmlDocument();
GoogleXMLdoc.Load(GoogleResponse.GetResponseStream());
XmlNode root = GoogleXMLdoc.DocumentElement;
XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_information");
//ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<b>Şehir : " + nodeList1.Item(0).SelectSingleNode("city").Attributes["data"].InnerText + "</b>";
XmlNodeList nodeList = root.SelectNodes("weather/current_conditions");
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<table cellpadding=\"5\"><tbody><tr><td style=\"width:50%;\"><b><big><nobr>" + nodeList.Item(0).SelectSingleNode("temp_c").Attributes["data"].InnerText + " °C | " + nodeList.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText + " °F</nobr></big></b></br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<b>Şuan:</b> " + nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + " " + nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerText + "</br>" + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + " " + nodeList.Item(0).SelectSingleNode("humidity").Attributes["data"].InnerText;
nodeList = root.SelectNodes("descendant::weather/forecast_conditions");
int i = 0;
foreach (XmlNode nod in nodeList)
{
if (i == 0)
{
i++;
continue;
}
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "</td><td align=\"center\">" + nod.SelectSingleNode("day_of_week").Attributes["data"].InnerText + "</br>" + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<img src=\"http://www.google.com" + nod.SelectSingleNode("icon").Attributes["data"].InnerText + "\" alt=\"" + nod.SelectSingleNode("condition").Attributes["data"].InnerText + "\">" + "</br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + nod.SelectSingleNode("low").Attributes["data"].InnerText + "°C" + "</br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + nod.SelectSingleNode("high").Attributes["data"].InnerText + "°C" + "</br>";
}
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "</td></tr></tbody></table>";
}
catch (System.Exception ex)
{
ViewBag.HavaDurumu = ex.Message;
}
finally
{
GoogleResponse.Close();
}
return PartialView();
}
I get the weather for specific location from google with this action.
Thanks.

There is currently an intermittent 403 Forbidden response to the Google Weather API that you are using. See Google Weather API 403 Error
The reason for the intermittent 403 response is not known but has been a problem since the 7th of August 2012.

Add a null reference check in your finally. Initializing GoogleResponse could fail, so it would still be null. Then you'll hit your finally block and get a null reference exception since GoogleResponse is null when you try to call .Close().
finally
{
if (GoogleResponse != null)
{
GoogleResponse.Close();
}
}

Related

QuickBooks Desktop Integration

I have a task to make a syncing service that can sync the sales records present in the Quick books point of sale into the local database.
How to integrate Quick books desktop point of sale and web application(c#) via web connector?
Code used :
public string sendRequestXML(string ticket, string strHCPResponse, string
strCompanyFileName,
string qbXMLCountry, int qbXMLMajorVers, int qbXMLMinorVers) {
if (Session["counter"] == null) {
Session["counter"] = 0;
}
string evLogTxt="WebMethod: sendRequestXML() has been called by
QBWebconnector" + "\r\n\r\n";
evLogTxt=evLogTxt+"Parameters received:\r\n";
evLogTxt=evLogTxt+"string ticket = " + ticket + "\r\n";
evLogTxt=evLogTxt+"string strHCPResponse = " + strHCPResponse +
"\r\n";
evLogTxt=evLogTxt+"string strCompanyFileName = " +
strCompanyFileName + "\r\n";
evLogTxt=evLogTxt+"string qbXMLCountry = " + qbXMLCountry + "\r\n";
evLogTxt=evLogTxt+"int qbXMLMajorVers = " +
qbXMLMajorVers.ToString() + "\r\n";
evLogTxt=evLogTxt+"int qbXMLMinorVers = " +
qbXMLMinorVers.ToString() + "\r\n";
evLogTxt=evLogTxt+"\r\n";
ArrayList req=buildRequest();
string request="";
int total = req.Count;
count=Convert.ToInt32(Session["counter"]);
if(count<total) {
request=req[count].ToString();
evLogTxt=evLogTxt+ "sending request no = " + (count+1) + "\r\n";
Session["counter"] = ((int) Session["counter"]) + 1;
}
else{
count=0;
Session["counter"]=0;
request="";
}
evLogTxt=evLogTxt+"\r\n";
evLogTxt=evLogTxt+"Return values: " + "\r\n";
evLogTxt=evLogTxt+"string request = " + request + "\r\n";
logEvent(evLogTxt);
return request;
}
It is creating log in the end, how will i fetch the data from the QBPOS?

how to insert multiple dynamic row value into the database

public void create(account_detail c, int jobcard_id)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
foreach (var details in c.Data)
{
cmd.CommandText = "insert into child_detail values ('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "');";
cmd.ExecuteNonQuery();
}
}
I am using this code but it only taking single value but I want to save the multiple values into the database ?
Try something like:
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
additionalText += ", ";
else
needComma = true;
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
Basic idea - prepare the string of teh command in the foreach loop, then execute the command once.

Getting all videos of a channel using youtube API

I want to get all videos of a single channel that i have its Id. The problem that I am getting only the channel informations.
this is the link that I am using:
https://gdata.youtube.com/feeds/api/users/UCdCiB_pNQpR0M_KkDG4Dz5A?v=2&alt=json&q=goal&orderby=published&max-results=10
That link is for the now-retired V2 API, so it will not return any data. Instead, you'll want to use V3 of the API. The first thing you'll need to do is register for an API key -- you can do this by creating a project at console.developers.google.com, setting the YouTube data API to "on," and creating a public access key.
Since you have your user channel ID already, you can jump right into getting the videos from it; note, however, that if you ever don't know the channel ID, you can get it this way:
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername={username}&key={YOUR_API_KEY}
With the channel ID, you can get all the videos from the channel with the search endpoint, like this:
https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId={channel id here}&maxResults=25&key={YOUR_API_KEY}
In this case, ordering by date is the same as the old V2 parameter for ordering by "published."
There are also a lot of other parameters you can use to retrieve videos while searching a channel; see https://developers.google.com/youtube/v3/docs/search/list for more details.
I thought I would share my final result using JavaScript. It uses the Google YouTube API key and UserName to get the channel ID, then pulls the videos and displays in a list to a given div tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>YouTube Channel Listing</title>
<script type="text/javascript">
function getJSONData(yourUrl) {
var Httpreq = new XMLHttpRequest();
try {
Httpreq.open("GET", yourUrl, false);
Httpreq.send(null);
} catch (ex) {
alert(ex.message);
}
return Httpreq.responseText;
}
function showVideoList(username, writediv, maxnumbervideos, apikey) {
try {
document.getElementById(writediv).innerHTML = "";
var keyinfo = JSON.parse(getJSONData("https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=" + username + "&key=" + apikey));
var userid = keyinfo.items[0].id;
var channeltitle = keyinfo.items[0].snippet.title;
var channeldescription = keyinfo.items[0].snippet.description;
var channelthumbnail = keyinfo.items[0].snippet.thumbnails.default.url; // default, medium or high
//channel header
document.getElementById(writediv).innerHTML += "<div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/user/" + username + "' target='_blank'>"
+ "<img src='" + channelthumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + channeltitle + "' title='" + channeltitle + "' /></a>"
+ "<div style='width:100%;text-align:center;'><h1><a href='https://www.youtube.com/user/" + username + "' target='_blank'>" + channeltitle + "</a></h1>" + channeldescription + "</div>"
+ "</div>";
var videoinfo = JSON.parse(getJSONData("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + userid + "&maxResults=" + maxnumbervideos + "&key=" + apikey));
var videos = videoinfo.items;
var videocount = videoinfo.pageInfo.totalResults;
// video listing
for (var i = 0; i < videos.length; i++) {
var videoid = videos[i].id.videoId;
var videotitle = videos[i].snippet.title;
var videodescription = videos[i].snippet.description;
var videodate = videos[i].snippet.publishedAt; // date time published
var videothumbnail = videos[i].snippet.thumbnails.default.url; // default, medium or high
document.getElementById(writediv).innerHTML += "<hr /><div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>"
+ "<img src='" + videothumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + videotitle + "' title='" + videotitle + "' /></a>"
+ "<h3><a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>" + videotitle + "</a></h3>" + videodescription + ""
+ "</div>";
}
} catch (ex) {
alert(ex.message);
}
}
</script>
</head>
<body>
<div id="videos"></div>
<script type="text/javascript">
showVideoList("USER_NAME", "videos", 25, "YOUR_API_KEY");
</script>
</body>
</html>
ADDITION - I also wrote a function to handle if you are using a channel ID instead of a UserName based account.
Here is that code:
function showVideoListChannel(channelid, writediv, maxnumbervideos, apikey) {
try {
document.getElementById(writediv).innerHTML = "";
var vid = getJSONData("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelid + "&maxResults=" + (maxnumbervideos + 1) + "&key=" + apikey);
var videoinfo = JSON.parse(vid);
var videos = videoinfo.items;
var videocount = videoinfo.pageInfo.totalResults;
var content = "<div style='height:600px;overflow-y:auto;'>";
for (var i = 0; i < videos.length - 1; i++) {
var videoid = videos[i].id.videoId;
var videotitle = videos[i].snippet.title;
var videodescription = videos[i].snippet.description;
var videodate = videos[i].snippet.publishedAt; // date time published
var newdate = new Date(Date.parse((videodate + " (ISO 8601)").replace(/ *\(.*\)/, "")));
var min = newdate.getMinutes();
if (min < 10) {
min = "0" + min;
}
if (newdate.getHours() > 12) {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + (newdate.getHours() - 12) + ":" + min + " PM";
} else if (newdate.getHours() == 12) {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + newdate.getHours() + ":" + min + " PM";
} else {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + newdate.getHours() + ":" + min + " AM";
}
var videothumbnail = videos[i].snippet.thumbnails.default.url; // default, medium or high
content += "<hr /><div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>"
+ "<img src='" + videothumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + videotitle + "' title='" + videotitle + "' /></a>"
+ "<h3><a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>" + videotitle + "</a></h3>" + videodescription + "<br />"
+ "<span style='color:#738AAD;font-size:Small;'>" + newdate + "</span>"
+ "</div>";
}
content += "</div>";
document.getElementById(writediv).innerHTML = content;
} catch (ex) {
alert(ex.message);
}
}
It is very easy method to get channel videos using your channel API key:
Step 1: You must have an YouTube account.
Step 2: Create your YouTube channel API key
Step 3: Create project console.developers.google.com,
<?php
$API_key = 'Your API key'; //my API key dei;
$channelID = 'Your Channel ID'; //my channel ID
$maxResults = 5;
$video_list =
json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?
order=date&part=snippet&channelId='.$channelID.
'&maxResults='.$maxResults.'&key='.$API_key.''));
?>
Example : https://www.googleapis.com/youtube/v3/channelspart=snippet&forUsername=
{username}&key={YOUR_API_KEY}
Here is the way to get all videos with only 2 quotas using YouTube Data API (v3)
First of all do a list on channels with part=contentDetails (1 quota) :
https://youtube.googleapis.com/youtube/v3/channels?part=contentDetails&id=[CHANNEL_ID]&key=[YOUR_API_KEY]
You will get this result :
{
...
"items": [
{
...
"contentDetails": {
"relatedPlaylists": {
"likes": "",
"uploads": "UPLOADS_PLAYLIST_ID"
}
}
}
]
}
Then take UPLOADS_PLAYLIST_ID and do a list on playlistItems with part=contentDetails (1 quota):
https://youtube.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId=[UPLOADS_PLAYLIST_ID]&key=[YOUR_API_KEY]
You will get this result:
{
...
"items": [
{
...
"contentDetails": {
"videoId": "VIDEO_ID",
"videoPublishedAt": "2022-10-27T16:00:08Z"
}
},
...
],
"pageInfo": {
"totalResults": 5648,
"resultsPerPage": 5
}
}
You got the list of the videos under items
You can of course change the size of this list by adding maxResults=50 (max value is 50)

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

How to use gettext placeholders?

I'm not a programmer, but I want to help translating a project written in vala (http://live.gnome.org/Vala/Tutorial) using gettext. I encountered a problem when I had to rearrange parts of a sentence using placeholders.
Example:
public void show_retrieving_similars() {
if(hint != ViewWrapper.Hint.SIMILAR || lm.media_info.media == null)
return;
errorBox.show_icon = false;
errorBox.setWarning("<span weight=\"bold\" size=\"larger\">" + _("Loading similar songs") + "</span>\n\n" + _("BeatBox is loading songs similar to") + " <b>" + lm.media_info.media.title.replace("&", "&") + "</b> by <b>" + lm.media_info.media.artist.replace("&", "&") + "</b> " + _("..."), null);
errorBox.show();
list.hide();
albumView.hide();
similarsFetched = false;
}
What do I need to do?
I haven't used vala and I haven't tested this, it looks like you need to replace
errorBox.setWarning("<span weight=\"bold\" size=\"larger\">" + _("Loading similar songs") + "</span>\n\n" + _("BeatBox is loading songs similar to") + " <b>" + lm.media_info.media.title.replace("&", "&") + "</b> by <b>" + lm.media_info.media.artist.replace("&", "&") + "</b> " + _("..."), null);
with
string title = lm.media_info.media.title.replace("&", "&");
string artist = lm.media_info.media.artist.replace("&", "&");
errorBox.setWarning(#"<span weight=\"bold\" size=\"larger\">Loading similar songs</span>\n\n BeatBox is loading songs similar to<b> $title </b>by<b> $artist </b>...", null);

Resources