Google Calendar API Error 405 - c#

I was trying out the Google Calendar API from this sample code but I am getting the following error:
Execution of authentication request returned unexpected result: 405
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Google.GData.Client.GDataRequestException: Execution of authentication request returned unexpected result: 405
Stack Trace:
Stack Trace:
[GDataRequestException: Execution of authentication request returned
unexpected result: 405]
_2.BusinessLogicLayer.LogicClasses.LeaveLogic.AddToGoogleCalendar() in C:\Users\Samsung\Desktop\Development\Ticketing
system\2.BusinessLogicLayer\LogicClasses\LeaveLogic.cs:375
_1.PresentationLayer.WebPages.LeaveRequest.tstbtn_Click(Object sender, EventArgs e) in C:\Users\Samsung\Desktop\Development\Ticketing
system\1.PresentationLayer\WebPages\LeaveRequest.aspx.cs:403
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Code:
string sGoogleUserName = "******#gmail.com";
string sGooglePassword = "*****";
Uri oCalendarUri = new Uri("http://www.google.com/calendar/feeds/" + sGoogleUserName + "/private/full");
//Initialize Calendar Service
CalendarService oCalendarService = new CalendarService("CalendarSampleApp");
oCalendarService.setUserCredentials(sGoogleUserName, sGooglePassword);
//Use Proxy
GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
oWebProxy.Credentials = CredentialCache.DefaultCredentials;
oWebProxy.UseDefaultCredentials = true;
oRequestFactory.Proxy = oWebProxy;
//Set Event Entry
EventEntry oEventEntry = new EventEntry();
oEventEntry.Title.Text = "Test Calendar Entry From .Net";
oEventEntry.Content.Content = "Hurrah!!! I posted my first Google calendar event through .Net";
//Set Event Location
Where oEventLocation = new Where();
oEventLocation.ValueString = "New Zealand";
oEventEntry.Locations.Add(oEventLocation);
//Set Event Time
When oEventTime = new When(new DateTime(2011, 5, 31, 9, 0, 0), new DateTime(2011, 5, 31, 9, 0, 0).AddHours(1));
oEventEntry.Times.Add(oEventTime);
//Set Additional Properties
ExtendedProperty oExtendedProperty = new ExtendedProperty();
oExtendedProperty.Name = "SynchronizationID";
oExtendedProperty.Value = Guid.NewGuid().ToString();
oEventEntry.ExtensionElements.Add(oExtendedProperty);
// CalendarService oCalendarService = GAuthenticate();
//Prevents This Error
//{"The remote server returned an error: (417) Expectation failed."}
System.Net.ServicePointManager.Expect100Continue = false;
//Save Event
oCalendarService.Insert(oCalendarUri, oEventEntry);

Comment the Proxy part it should work:
////Use Proxy
//GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
//WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
//oWebProxy.Credentials = CredentialCache.DefaultCredentials; //oWebProxy.UseDefaultCredentials = true;
//oRequestFactory.Proxy = oWebProxy;

Related

Stopped at System.Diagnostics.Process.Start - OAuth 2.0 to Google for Windows apps

I am following below libraries and samples to help me implement the OAuth 2.0 flow described form this Gooolge’s developers recommend codes(https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthDesktopApp/OAuthDesktopApp/MainWindow.xaml.cs),
It can runs successfully.
But when I created a new WinForms project to reproduce code, my code was same as the sample : (https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthDesktopApp/OAuthDesktopApp/MainWindow.xaml.cs).
it showed “InnerException: System.Exception {System.ComponentModel.Win32Exception}” and
stopped at “Application.Run(new Form1());” when I build this project and clicked the ‘button1’.
[C#]
private async void button1_Click(object sender, EventArgs e)
{
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort());
output("redirect URI: " + redirectURI);
var http = new HttpListener();
http.Prefixes.Add(redirectURI);
output("Listening..");
http.Start();
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
authorizationEndpoint,
System.Uri.EscapeDataString(redirectURI),
clientID,
state,
code_challenge,
code_challenge_method);
System.Diagnostics.Process.Start(authorizationRequest); // <===== key! stops here
var context = await http.GetContextAsync();
this.Activate();
var response = context.Response;
string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please return to the app.</body></html>");
var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
var responseOutput = response.OutputStream;
Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
{
responseOutput.Close();
http.Stop();
Console.WriteLine("HTTP server stopped.");
});
if (context.Request.QueryString.Get("error") != null)
{
output(String.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error")));
return;
}
if (context.Request.QueryString.Get("code") == null
|| context.Request.QueryString.Get("state") == null)
{
output("Malformed authorization response. " + context.Request.QueryString);
return;
}
var code = context.Request.QueryString.Get("code");
var incoming_state = context.Request.QueryString.Get("state");
if (incoming_state != state)
{
output(String.Format("Received request with invalid state ({0})", incoming_state));
return;
}
output("Authorization code: " + code);
performCodeExchange(code, code_verifier, redirectURI);
}
The error message:
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
Win32Exception: 系統找不到指定的檔案。
此例外狀況原先在此呼叫堆疊擲回:
System.Diagnostics.Process.StartWithCreateProcess(System.Diagnostics.ProcessStartInfo)
System.Diagnostics.Process.Start()
System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo)
System.Diagnostics.Process.Start(string)
OAuthDesktopApp_改成winForm_20220921.Form1.button1_Click(object, System.EventArgs) 位於 Form1.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Threading.Tasks.Task.ThrowAsync.AnonymousMethod__139_0(object)
I find comment out this line can pass the program, so it stop here.
...
[C#]
**System.Diagnostics.Process.Start(authorizationRequest);** // <===== key! stops here
var context = await http.GetContextAsync();
this.Activate();
...
Any suggestion is welcome.

Using iTextSharp for HTML to PDF with images on header, footer and body, "Cannot access a closed Stream"

I'm using iTextSharp and XMLWorker 5.5.12 to convert HTML to PDF, I need to generate a header, a footer and body content.
I was able to generate all with text using a Page Event, the problem comes when I try to insert images in the body and in the Page Event, as soon as I use images in both the parser.Parse(reader); line throws error Cannot access a closed Stream..
This is the code I've come so far:
protected ActionResult ViewPdf(string viewName, object model, ViewDataDictionary viewData = null,
iTextSharp.text.Rectangle size = null,
float marginLeft = 10f, float marginRight = 10f,
float marginTop = 10f, float marginBottom = 10f,
IEnumerable<PDFFragmentBaseViewModel> fragments = null)
{
if (size == null) size = iTextSharp.text.PageSize.LETTER;
using (iTextSharp.text.Document document = new iTextSharp.text.Document(size, marginLeft, marginRight, marginTop, marginBottom))
{
using (var outStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
writer.CloseStream = false;
// page event
//if (pageEvent != null)
// writer.PageEvent = pageEvent;
// css
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
//if (cssPath != null)
// cssResolver.AddCssFile(cssPath, true);
//Register Image Procesor
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(new ResourceImageHtmlTagProcessor(), new[] { "resimg" });
// html
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(tagProcessorFactory);
// pipelines
PdfWriterPipeline pdfPipeline = new PdfWriterPipeline(document, writer);
HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfPipeline);
CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
// parse
XMLWorker worker = new XMLWorker(cssPipeline, true);
XMLParser parser = new XMLParser(worker);
writer.CloseStream = false;
List<PDFFragmentViewModel> _frags = null;
if (fragments != null)
{
_frags = new List<PDFFragmentViewModel>();
foreach (var frag in fragments)
{
_frags.Add(new PDFFragmentViewModel {
Content = REC0Utils.RenderRazorViewToString(frag.ViewName, ControllerContext, new object { }, viewData ?? ViewData),
Alignment = frag.Alignment,
Leading = frag.Leading,
LLX = frag.LLX,
LLY = frag.LLY,
URX = frag.URX,
URY = frag.URY
});
}
//string htmlHeader = "<!DOCTYPE html><html><body><table style=\"width: 100%; border: 1px solid black;\"><tr><td>A</td><td>B</td></tr></table></body></html>";
//string htmlHeader = REC0Utils.RenderRazorViewToString(headerViewName, ControllerContext, headerModel, viewData ?? ViewData);
writer.PageEvent = new HtmlPageEventHelper(_frags);
}
document.Open();
// Render the view xml to a string, then parse that string into an XML dom.
string xmltext = REC0Utils.RenderRazorViewToString(viewName, this.ControllerContext, model, viewData == null ? ViewData : viewData);
using (var reader = new StringReader(xmltext))
{
parser.Parse(reader);
}
// Close and get the resulted binary data.
document.Close();
// Send the binary data to the browser.
return new BinaryContentResult(outStream.ToArray(), "application/pdf");
}
}
// Parse the XML into the iTextSharp document.
//TextReader reader = new StringReader(xmltext);
//XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
//XMLParser textHandler = new XMLParser(doc);
//textHandler.Parse(xmldoc);
}
And this is the code for the Page Event:
public class HtmlPageEventHelper : PdfPageEventHelper
{
List<PDFFragmentViewModel> _fragments;
public HtmlPageEventHelper(List<PDFFragmentViewModel> fragments)
{
this._fragments = fragments;
}
public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
var _instance = XMLWorkerHelper.GetInstance();
// css
ICSSResolver cssResolver = _instance.GetDefaultCssResolver(false);
//Register Image Procesor
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(new ResourceImageHtmlTagProcessor(), new[] { "resimg" });
// html
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(tagProcessorFactory);
// pipelines
PdfWriterPipeline pdfPipeline = new PdfWriterPipeline(document, writer);
HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfPipeline);
CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
// parse
XMLWorker worker = new XMLWorker(cssPipeline, true);
XMLParser parser = new XMLParser(worker);
foreach (var _frag in _fragments)
{
ColumnText ct = new ColumnText(writer.DirectContent);
//using (var reader = new StringReader(_frag.Content))
//{
// parser.Parse(reader);
//}
_instance.ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(_frag.Content));
//ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-20), 10, Element.ALIGN_MIDDLE);
ct.SetSimpleColumn(
_frag.LLX.HasValue ? document.GetLeft(_frag.LLX.Value) : document.Left,
_frag.LLY.HasValue ? document.GetTop(_frag.LLY.Value) : document.Top,
_frag.URX.HasValue ? document.GetRight(_frag.URX.Value) : document.Right,
_frag.URY.HasValue ? document.GetBottom(_frag.URY.Value) : document.Bottom,
_frag.Leading, _frag.Alignment);
ct.Go();
}
}
}
I've been investigating and I saw somewhere a suggestion to remove the using statements, when I remove them I get a different error:
Can not find own context
Can anyone please shed some light on this?
UPDATE:
As requested by a comment this is the Stack Trace of the Can not find own context error.
at iTextSharp.tool.xml.XMLWorker.EndElement(String tag, String ns)
at iTextSharp.tool.xml.parser.XMLParser.EndElement()
at iTextSharp.tool.xml.parser.state.ClosingTagState.Process(Char character)
at iTextSharp.tool.xml.parser.XMLParser.ParseWithReader(TextReader reader)
at iTextSharp.tool.xml.parser.XMLParser.Parse(TextReader reader)
at MvcREC0.WebUI.Controllers.BaseController.ViewPdf(String viewName, Object model, ViewDataDictionary viewData, Rectangle size, Single marginLeft, Single marginRight, Single marginTop, Single marginBottom, IEnumerable`1 fragments) in C:\Pr0g\MVCRec0\WebUI\Controllers\BaseController.cs:line 225
at MvcREC0.WebUI.Controllers.Crudere`6.<Index>d__8.MoveNext() in C:\Pr0g\MVCRec0\WebUI\Controllers\Cruder.cs:line 688
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar)
at System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar)
And this is the Stack Trace for the Inner Exception:
at iTextSharp.tool.xml.pipeline.AbstractPipeline.GetLocalContext(IWorkerContext context)
at iTextSharp.tool.xml.pipeline.html.HtmlPipeline.Close(IWorkerContext context, Tag t, ProcessObject po)
at iTextSharp.tool.xml.XMLWorker.EndElement(String tag, String ns)
Indeed, what you try to do is not supported by the XMLWorker architecture. (I'm actually a bit surprised about this; I think I even in some earlier comment here or there claimed it should work.)
In short
The XMLWorker architecture does not allow overlapping usages from the same thread. It does allow overlapping usages from different threads and non-overlapping usages in any threading situation, though.
As your headers and footers appear not to depend on the actual page contents, I'd recommend you switch to a two-pass process: In the first pass create the document body using a Document and a PdfWriter as above, merely without the event listener; in the second pass stamp the headers and footers onto it using a PdfReader and a PdfStamper. Alternatively you can try the work-around posted at the end of this answer.
In detail
The XMLWorker keeps a context for the current parsing operation in a Thread Data Slot (in Java in a ThreadLocal).
The contents of the context in the current thread are initialized at the start of XMLParser.ParseWithReader, and the whole context of the current thread is dropped at its end.
The method XMLParser.ParseWithReader eventually is used by each XMLParser.Parse overload and also by each XMLWorkerHelper.parseXHtml overload.
As soon as two parsing attempts using the XMLWorker architecture - e.g. parsing attempts in a page event listener and a parsing attempt filling the body (unless the latter is clearly limited to a single page) - overlap, therefore, they get into each other's way and the attempt finishing first removes the context also used by the other.
A work-around
There is a work-around for this issue, at least for situations like the one at hand, if one is ok with using reflection and one's runtime environment allows that:
Whenever one switches to another attempt, one can store the current context value and replace it with a value appropriate for the parsing coming up. As context is declared private, this requires reflection.
In the case at hand that would be:
public class HtmlPageEventHelper : PdfPageEventHelper
{
List<PDFFragmentViewModel> _fragments;
FieldInfo context;
public HtmlPageEventHelper(List<PDFFragmentViewModel> fragments)
{
this._fragments = fragments;
context = typeof(XMLWorker).GetField("context", BindingFlags.NonPublic | BindingFlags.Static);
}
public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
{
[...]
// parse
XMLWorker worker = new XMLWorker(cssPipeline, true);
XMLParser parser = new XMLParser(worker);
LocalDataStoreSlot contextSlot = (LocalDataStoreSlot) context.GetValue(worker);
object contextData = Thread.GetData(contextSlot);
Thread.SetData(contextSlot, null);
try
{
foreach (var _frag in _fragments)
{
ColumnText ct = new ColumnText(writer.DirectContent);
//using (var reader = new StringReader(_frag.Content))
//{
// parser.Parse(reader);
//}
_instance.ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(_frag.Content));
//ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-20), 10, Element.ALIGN_MIDDLE);
ct.SetSimpleColumn(
_frag.LLX.HasValue ? document.GetLeft(_frag.LLX.Value) : document.Left,
_frag.LLY.HasValue ? document.GetTop(_frag.LLY.Value) : document.Top,
_frag.URX.HasValue ? document.GetRight(_frag.URX.Value) : document.Right,
_frag.URY.HasValue ? document.GetBottom(_frag.URY.Value) : document.Bottom,
_frag.Leading, _frag.Alignment);
ct.Go();
}
}
finally
{
Thread.SetData(contextSlot, contextData);
}
}
}

The ContinuousProcessing parameter is no longer supported.NPGSQL

I just upgraded my npgsql from 2.5.5 to 3.1.1 and i am getting this runtime error.
My DbConnection class
public static string ServerConnectionString()
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
Host = ConfigurationManager.AppSettings["Server"],
Username = ConfigurationManager.AppSettings["UserId"],
Database = "postgres",
Password = ConfigurationManager.AppSettings["Password"],
CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["CommandTimeout"]),
ApplicationName = EverestEnums.ConnectionApplicationName.EverestServerChecker.ToString(),
// MaxPoolSize = 200,
// SyncNotification = true,
KeepAlive = 1,
ConnectionLifeTime = 1,
// MinPoolSize = 1,
Pooling = false
};
return connectionStringBuilder.ConnectionString;
}
Stack Trace
[NotSupportedException: The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
Npgsql.NpgsqlConnectionStringBuilder.set_ConnectionLifeTime(Int32 value) +62
Everest.Net.DatabaseLayer.DBFactory.DbConnection.ServerConnectionString() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\DBConnection.cs:13
Everest.Net.DatabaseLayer.DBFactory.DBOperations.IsServerAvailable() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\DBOperations.cs:216
Everest.Net.DatabaseLayer.DBFactory.ServerConnectivity.IsDbServerAvailable() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\ServerConnectivity.cs:7
Everest.Net.BusinessLayer.DBFactory.ServerConnectivity.IsDbServerAvailable() in E:\Everest_PES\Everest.Net.BusinessLayer\DBFactory\ServerConnectivity.cs:12
Everest.Net.Web.Global.Application_Start(Object sender, EventArgs e) in E:\Everest_PES\Everest.Net.Web\Global.asax.cs:15
[HttpException (0x80004005): The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +544
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343
[HttpException (0x80004005): The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +112
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +712
As it was working fine before.But there was some issue with connection pooling.And then i upgraded npgsql and this rumtime error.Any Help.
It looks like that exception is thrown when you get or set the ConnectionLifeTime property on the NpgsqlConnectionStringBuilder. The property is obsolete and replaced by the Connection Idle Lifetime property now (see http://www.npgsql.org/doc/migration.html). Try to use this instead:
public static string ServerConnectionString()
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
Host = ConfigurationManager.AppSettings["Server"],
Username = ConfigurationManager.AppSettings["UserId"],
Database = "postgres",
Password = ConfigurationManager.AppSettings["Password"],
CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["CommandTimeout"]),
ApplicationName = EverestEnums.ConnectionApplicationName.EverestServerChecker.ToString(),
// MaxPoolSize = 200,
// SyncNotification = true,
KeepAlive = 1,
ConnectionIdleLifetime = 1,
// MinPoolSize = 1,
Pooling = false
};
return connectionStringBuilder.ConnectionString;
}

COMException (0x80005000): Unknown error - UserPrincipal.set_GivenName(String value)

I have the following code which is called inside of an ASP.NET application:
public DomainUserInfo GetDomainUserInfoByName(string domain, string firstName, string lastName)
{
string[] domainArray = domain.Split(',');
foreach (string d in domainArray)
{
var principalContext = new PrincipalContext(ContextType.Domain, d);
var userPrincipal = new UserPrincipal(principalContext) {GivenName = firstName, Surname = lastName};
using (var searcher = new PrincipalSearcher(userPrincipal))
{
userPrincipal = (UserPrincipal) searcher.FindOne();
}
if (userPrincipal != null)
{
var domainUserInfo = new DomainUserInfo
{
FirstName = userPrincipal.GivenName,
LastName = userPrincipal.Surname,
Email = userPrincipal.EmailAddress,
LanID = userPrincipal.SamAccountName,
Extension = userPrincipal.VoiceTelephoneNumber,
DomainName = d,
NTAccountName = userPrincipal.Sid.Translate(typeof (NTAccount)).ToString()
};
return domainUserInfo;
}
}
return null;
}
It works when deployed on some servers but not on others, where it throws the exception:
[COMException (0x80005000): Unknown error (0x80005000)]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +386081
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_AdsObject() +31
System.DirectoryServices.PropertyValueCollection.PopulateList() +21
System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +49
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +135
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +288
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +118
System.DirectoryServices.AccountManagement.PrincipalContext.ContextForType(Type t) +34
System.DirectoryServices.AccountManagement.Principal.GetStoreCtxToUse() +37
System.DirectoryServices.AccountManagement.UserPrincipal.set_GivenName(String value) +17
Mfc.Inv.RM.Framework.ActiveDirectory.ActiveDirectoryManager.GetDomainUserInfoByName(String domain, String firstName, String lastName) +167
It looks like this is occurring on the line:
var userPrincipal = new UserPrincipal(principalContext) {GivenName = firstName, Surname = lastName};
when trying to set the GivenName property of the UserPrincipal object.
I'm totally stuck as to what could be causing this, especially since it works on some servers and not others. I already tried writing a console application that calls the same code it works on all of the servers, so I am guessing it has to be something to do with IIS.
here is what I am doing and if you were to hover over userFind or do a QuickWatch on it you will see the following information. also notice the IdentityType.SamAccountName that I am passing
var pc = new PrincipalContext(ContextType.Domain, domainName, null, null);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username);

C#/SQL Parse Error

I am trying to build a register user script using C# and SQL. However when wver I try to add the users details to the database I run into a parse error. This error is below
There was an error parsing the query. [ Token line number = 1,Token line offset = 38,Token in error = = ]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [ Token line number = 1,Token line offset = 38,Token in error = = ]
Source Error:
Line 48: {
Line 49: var db = Database.Open("Database");
Line 50: var users = db.QuerySingle("SELECT * FROM Users WHERE Username = ", username);
Line 51: if (users == null)
Line 52: {
Source File: c:\Users\***\Documents\Visual Studio 2012\WebSites\CatSystem\Account\Login.cshtml Line: 50
Stack Trace:
[SqlCeException (0x80004005): There was an error parsing the query. [ Token line number = 1,Token line offset = 38,Token in error = = ]]
System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr) +136
System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan() +798
System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options) +363
System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior) +59
System.Data.SqlServerCe.SqlCeCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader() +12
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +152
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
ASP._Page_Account_Login_cshtml.Execute() in c:\Users\***\Documents\Visual Studio 2012\WebSites\CatSystem\Account\Login.cshtml:50
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +69
System.Web.WebPages.WebPage.ExecutePageHierarchy() +151
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +249
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18010
The script I am using is
#{// Initialize page
var email = "";
var username = "";
var password = "";
var confirmPassword = "";
var firstname = "";
var lastname = "";
var housenumberorname = "";
var street = "";
var city = "";
var county = "";
var postcode = "";
var tel = "";
var mobile = "";
var dob = "";
var ErrorMessage = "";
// If this is a POST request, validate and process data
if (IsPost)
{
email = Request.Form["email"];
username = Request.Form["username"];
password = Request.Form["password"];
confirmPassword = Request.Form["confirmPassword"];
firstname = Request.Form["firstname"];
lastname = Request.Form["lastname"];
housenumberorname = Request.Form["housenumberorname"];
street = Request.Form["street"];
city = Request.Form["city"];
county = Request.Form["county"];
postcode = Request.Form["postcode"];
tel = Request.Form["tel"];
mobile = Request.Form["mobile"];
dob = Request.Form["dob"];
if (username.IsEmpty() || password.IsEmpty()) {
ErrorMessage = "You must specify both email and password.";
}
if (password != confirmPassword)
{
ErrorMessage = "Password and confirmation do not match.";
}
// If all information is valid, create a new account
if (ErrorMessage=="")
{
var db = Database.Open("Database");
var user = db.QuerySingle("SELECT * FROM Users WHERE Username = ", username);
if (user == null)
{
db.Execute("INSERT INTO User (Username, Password, Firstname, Lastname, House, Street, City, County, Postscode, Tel, Mobile, Email, Dob) VALUES (#0, #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12)", username, password, firstname, lastname, housenumberorname, street, city, county, postcode, tel, mobile, email, dob);
WebSecurity.CreateAccount(username, password, false);
// Navigate back to the homepage and exit
Response.Redirect("~/");
}
else
{
ErrorMessage = "Email address is already in use.";
}
}
}
}
#if (ErrorMessage!="")
{
<p>#ErrorMessage</p>
<p>Please correct the errors and try again.</p>
}
I assume there is something wrong with the SQL command but as I am unfamiliar with MS SQL I can not see the issue. Any help with this would be appreciated.
The SQL is not valid. If Username is a VARCHAR or CHAR type, you need to enclose the value in ', though a better option is to use a parameterized query, as using string concatenation/formatting means your application is open to SQL Injection .
var users = db.QuerySingle(
string.Format("SELECT * FROM Users WHERE Username = '{0}'",
username));
You should change your code to use the parametrization as you have in your insert:
var user = db.QuerySingle("SELECT * FROM Users WHERE Username = #0", username);
Currently your query does not contain the username from username it is just
SELECT * FROM Users WHERE Username =
Which is invalid sytax.
From : http://wekeroad.com/2011/01/13/someone-hit-their-head
var db = Database.Open("TDL");
var selectQueryString = "SELECT * FROM Articles WHERE slug = #0";
show = db.QuerySingle(selectQueryString, slug);

Categories

Resources