I want to get the most current questions from Stack Overflow using the Stacky C# library for the Stack Exchange API.
I took the example code and tried to run it but it hangs when it comes to returning data from the Stack Exchange website.
StackyClient client = new StackyClient("0.9", "", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
var o = new QuestionOptions();
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o); <--- program hangs here 4ever
What am I doing wrong?
I also saw that I can register my application to get an API Key. But that is not necessary to make it run in the first place, is it?
Edit
If I remove the lines
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
it works and returns all questions. Also if I add the line
o.Max = 50;
instead, then it does not work either.
Edit 2
Now it works - rebooted my computer.
BTW I used that code in the end
var o = new QuestionOptions();
o.FromDate = DateTime.UtcNow.AddMinutes(-20);
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o);
And
o.Max
expects an Unix Epoch time, not a number of maximum posts.
Try changing the version specified in the StackyClient constructor from "0.9" to "1.1". I get a JSON parse error on the client.GetQuestions(o) line when the version is "0.9", but it runs fine with "1.1".
Using the latest Stacky code from bitbucket there is no longer a QuestionOptions parameter to GetQuestions. Also using version 0.9 of the API causes Stacky to crash, but according to this version 1.x is deprecated, so maybe 0.9 is removed?
StackyClient client = new StackyClient("2.1", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
//var o = new QuestionOptions();
//o.FromDate = DateTime.Now.AddMinutes(-10.0);
//o.ToDate = DateTime.Now;
//o.IncludeAnswers = false;
//o.IncludeBody = false;
//o.IncludeComments = false;
//o.SortBy = QuestionSort.Creation;
//o.SortDirection = SortDirection.Descending;
QuestionSort sort = QuestionSort.Creation;
SortDirection sortDir = SortDirection.Descending;
int page = 1;
int pageSize = 100;
DateTime fromDate = DateTime.Now.AddMinutes(-10.0);
DateTime toDate = DateTime.Now;
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}
Or, just remove the date and see if you get any results.
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize);//, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}
Related
I am running a windows service which runs every 6 hours and generates files. For some files I want to generate them only once a month.
var todaysDate = DateTime.Now.Date;
var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
var fileGenerated = false;
if (Convert.ToBoolean(firstOfMonth))
{
var fileToUploadOne = GenerateFileOne("sproc_name");
var fileToUploadTwo = GenerateFileTwo("sproc_name");
fileGenerated = true;
}
How can I make sure the file is generate only once a month.
Updates: Once is month means, generate file one time each month, so that when the services runs every X hours, it does not generate the file over and over again.
The idea is based on saving somewhere on a disk date of last file generation and checking if new month has begun.
You could try this (necessary comments are in code):
class Program
{
// some safe location
private static var path = "";
static void Main(string[] args)
{
//get the saved tade
var saveDate = GetLastSavingDate();
var today = DateTime.Now;
//var todaysDate = DateTime.Now.Date;
//var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
//var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
var fileGenerated = false;
// check if the difference in months exceeded 1 - this will be true on every 1st of new month, for example 8 - 7 or even 1 - 12
if(Math.Abs(today.Month - saveDate.Month) >= 1)
{
var filetouploadone = generatefileone("sproc_name");
var filetouploadtwo = generatefiletwo("sproc_name");
filegenerated = true;
// save date
File.WriteAllText(path, JsonConvert.SerializeObject(today));
}
}
//method to get saved date
private static DateTime GetLastSavingDate()
{
var dt = new DateTime();
return JsonConvert.DeserializeAnonymousType(File.ReadAllText(path), dt);
}
}
I have taken Console App just for the sake of example, this can be easily applied in WinForms as well.
I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?
//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
rndString += c;
}
string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();
//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;
//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;
UserCreateStatus result = UserController.CreateUser(ref oUser);
if (result == UserCreateStatus.Success)
{
RoleController oDnnRoleController = new RoleController();
//Get the role information
RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
// RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
//Assign to user
oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
// oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}
The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.
I want to consume SAP web service into my c# application. For that i wrote one block of code given below.
NetworkCredential ntobj = new NetworkCredential();
ZWEBSERVICE_INTERNAL_ORDER2 zClassobj = new ZWEBSERVICE_INTERNAL_ORDER2();
ZbapiFiCreateInternalOrder zMethodObj = new ZbapiFiCreateInternalOrder();
ZbapiFiCreateInternalOrderResponse zMethodResobj = new ZbapiFiCreateInternalOrderResponse();
ntobj.UserName = "alpldev";
ntobj.Password = "alpl123";
zClassobj.PreAuthenticate = true;
zClassobj.Credentials = ntobj;
zMethodObj.IDriverNo = "KD00000014";
zMethodObj.IPlant = "1001";
zMethodObj.ITripNo = "1001201406140027";
zMethodObj.IVhclNo = "AP29Q8639";
zMethodResobj = zClassobj.ZbapiFiCreateInternalOrder(zMethodObj);
but at last line i got "underlying connection established was closed. unexpected format was send" error.
please help me...
I'm actually using a soap service for a SAP WebService and I think I know what the problem is. You have to do first a Request including the QaaWsHeader and the ReportBlock configuration, then create the Request and finally with help with the ServicesSoapClient make the method to send your result.
Use this as an example, I hope this will help, good luck
Sellers.QaaWSHeader qaawsHeaderDatos = new Sellers.QaaWSHeader();
Sellers.GetReportBlock_WBS_Sellers getReportBlock = new Sellers.GetReportBlock_WBS_Sellers();
getReportBlock.login = userWS;
getReportBlock.password = passWS;
getReportBlock.refresh = true;
getReportBlock.startRow = 0;
getReportBlock.startRowSpecified = true;
getReportBlock.endRow = 1000;
getReportBlock.endRowSpecified = true;
Sellers.GetReportBlock_WBS_Sellers_Request WSRequest = new Sellers.GetReportBlock_WBS_Sellers_Request(qaawsHeaderDatos, getReportBlock);
Sellers.BIServicesSoap BiService = new Sellers.BIServicesSoapClient();
Sellers.GetReportBlock_WBS_Sellers_Response FinalResponse = BiService.GetReportBlock_WBS_Sellers(WSRequest);
object[][] yourTable = FinalResponse.table;
This my one method primaryKey of my model is 'PlanetKey'
Graph graph = new Graph();
long lastGraphID = 1000;
//graph.GraphID = lastGraphID;
graph.ItemType = enumType;
graph.GraphItemTitle = title;
graph.GraphItemDescription = statusMessage;
graph.GraphItemUserFullName = null;
graph.GraphItemURL = url;
graph.ItemSummary = title + ": " + statusMessage; ;
graph.ItemCreatedOn = DateTime.UtcNow.ToLocalTime();
//graph.GraphID = lastGraphID;
graph.GraphCustomURL = null;
graph.DbType = "OFFLINE";
graph.ItemOwnerGraphID = ItemOwnerGraphID;
graph.ItemUserID = userInfoId;
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedCareerTreeNodeId = 0;
graph.PRIMARYTaggedCareerTreeSerialNumber = "1";
graph.PRIMARYTaggedSkillTreeNodeId = 0;
graph.PRIMARYTaggedSkillTreeSerialNumber = "1";
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedToolTreeNodeId = 0;
graph.PRIMARYTaggedToolTreeSerialNumber = "1";
graph.CountReactions = 0;
graph.CountResponses = 0;
graph.CountRatings = 0;
graph.AverageRating = 0;
graph.CountRatings = 0;
graph.CountUses = 0;
graph.CountViews = 0;
graph.isReported = false;
graph.isPSKverified = false;
graph.isPSKbanned = false;
graph.isPSKresource = false;
graph.AccessAllowedCode = 0;
graph.AgeRestrictionCode = loginUserCurrentAge;
graph.isHidden = false;
GraphsController GraphsControllerObject = new GraphsController();
long returnGraphId = GraphsControllerObject.CreateGraphIdByModel(graph);
this is another what i am calling to
public long CreateGraphIdByModel(Graph graph)
{
try
{
if (ModelState.IsValid)
{
db.Graphs.Add(graph);
db.SaveChanges();
return graph.GraphID;
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return graph.GraphID;
}
this is showing me eeror in db.SaveChanges()
what m i doing wrong with this code i just wanna pass my parameter using model as crud of mvc4
To know what the error is: You need to look at the inner exception, it will tell you precisely what the problem is.
You can inspect the exceptions innerException property. It will be an EF exception with a list of errors.
The error says, Error converting datetime2 to datetime
Entity framework handles all the dates as a Datetime2, so, if you fields in the database are Datetime, this could be a problem. Populating all the date fields and changing the datatype, are the most commom solutions
Copied from here: 'datetime2' error when using entity framework in VS 2010 .net 4.0
I am LINQ to input information from a Database. I have my try.catch block set up to catch these exceptions. However I believe I ran into a sore spot where I am attempting to see what the message is but it just bypass printing the message to me and goes directly to error page. Here is an example of the code I have so far. I would love to get some input on why this seems to be acting so strange.
private void CreateEntry()
{
var date = DateTime.Today;
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
//Try to create an entry for the database. Upon failure, sends the exception to ThrowDbError();
try
{
ResidenceHallInspection rhi = new ResidenceHallInspection();
rhi.versionId = version.id;
rhi.submitDate = DateTime.Now;
rhi.CheckInOrOut = ddlCheck.SelectedItem.Text;
rhi.Id = txtId.Text;
rhi.FirstName = txtFirstName.Text;
rhi.MiddleName = txtMiddleName.Text;
rhi.LastName = txtLastName.Text;
rhi.Walls = chbxWalls.SelectedItem.Text;
rhi.Windows = chbxWindows.SelectedItem.Text;
rhi.Blinds = chbxBlinds.SelectedItem.Text;
rhi.Couch = chbxCouch.SelectedItem.Text;
rhi.CommonRoomCouch = chbxCRCouch.SelectedItem.Text;
rhi.CommonRoomChair = chbxCRChair.SelectedItem.Text;
rhi.Doors = chbxDoors.SelectedItem.Text;
rhi.Carpet = chbxCarpet.SelectedItem.Text;
rhi.Ceiling = chbxCeiling.SelectedItem.Text;
rhi.CommonRoomCounter = chbxCRCounter.SelectedItem.Text;
rhi.Cabinet = chbxCabinet.SelectedItem.Text;
rhi.Phone = chbxPhone.SelectedItem.Text;
rhi.Bed = chbxBed.SelectedItem.Text;
rhi.Desk = chbxDesk.SelectedItem.Text;
rhi.DeskChairs = chbxDeskChair.SelectedItem.Text;
rhi.Tub = chbxTub.SelectedItem.Text;
rhi.Vanity = chbxVanity.SelectedItem.Text;
rhi.Notes = txtNotes.Text;
rhi.Building = txtResHall.Text;
rhi.ApartmentNumber = txtSuitNo.Text;
rhi.BedSpace = txtBedSpace.Text;
house.AddToResidenceHallInspections(rhi);
house.SaveChanges();
}
catch (Exception oe)
{
ThrowDbError(oe);
Response.Write(oe.InnerException);
}
}
/*=================================================*/
/*Possible Errors */
/*=================================================*/
private void ThrowDbError(Exception oe)
{
Response.Write(oe.Source);
house.Dispose();
Session.Contents.Add("FormException", oe);
Response.Redirect("/Database-Error/", true);
}
The most likely reason for that to happen is that you are running the database version query outside the try/catch block. Any exception in this db access code will not be handled by the code you have shown above.
Try extending your try block to also include the db access code:
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
and see if this time the error is caught.