I have developed a windows services which work to send email for neglected lead after 7 days.
When I run code in my machine it work and continue. But when I install in a Windows services then some error occurs:
using (OrganizationServiceProxy serviceProxy =
new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
{
IOrganizationService service = (IOrganizationService)serviceProxy;
ColumnSet Indexcol = new ColumnSet(new string[] { columnname });
QueryByAttribute indexattribute = new QueryByAttribute();
indexattribute.EntityName = EntityName;
indexattribute.Attributes.AddRange(RangeAttribute);
indexattribute.Values.AddRange(RangeValues);
indexattribute.ColumnSet = Indexcol;
RetrieveMultipleRequest req_index = new RetrieveMultipleRequest();
req_index.Query = indexattribute;
try {
// Error occurs when this line executes
RetrieveMultipleResponse resp_index =
(RetrieveMultipleResponse)service.Execute(req_index);
EntityCollection mcs_index = resp_index.EntityCollection;
}
}
and error is
The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
or from the configuration behavior) on the server in
order to send the exception information back to the client, or turn on
tracing as per the Microsoft .NET Framework 3.0 SDK documentation and
inspect the server trace logs.
kindly guide me I am stuck here. :(
Related
I use CosmosClient from SDK Microsoft.Azure.Cosmos 3.28.0 in ASP.NET Core 3.1 in Azure Durable Function. This client is getting and sending data from/to my cosmos instance (Core (SQL)) and it works fine but I see that it constantly throws exception in following http request for metadata
GET 169.254.169.254/metadata/instance
System.Net.Http.HttpRequestException: An attempt was made to access a socket in a way forbidden by its access permissions.
I use following configuration:
private static void RegisterCosmosDbClient(ContainerBuilder builder)
{
builder.Register(c => new SocketsHttpHandler()
{
PooledConnectionLifetime = TimeSpan.FromMinutes(10), // Customize this value based on desired DNS refresh timer
MaxConnectionsPerServer = 20, // Customize the maximum number of allowed connections
}).As<SocketsHttpHandler>().SingleInstance();
builder.Register(
x =>
{
var cosmosDbOptions = x.Resolve<CosmosDbOptions>();
var socketsHttpHandler = x.Resolve<SocketsHttpHandler>();
return new CosmosClient(cosmosDbOptions.ConnectionString, new CosmosClientOptions()
{
ConnectionMode = ConnectionMode.Direct,
PortReuseMode = PortReuseMode.PrivatePortPool,
IdleTcpConnectionTimeout = new TimeSpan(0, 23, 59, 59),
SerializerOptions = new CosmosSerializationOptions()
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
},
HttpClientFactory = () => new HttpClient(socketsHttpHandler, disposeHandler: false)
});
})
.AsSelf()
.SingleInstance();
}
I also tried approach with passing IHttpClientFactory from this blog but it didn't help.
It looks like there are no new sockets available in your environment therefore you are getting the socket forbidden error. Please review how to manage connection for Azure Cosmos DB clients and you should use a singleton Azure Cosmos DB client for the lifetime of your application to resolve the issue. In case if you still facing the issue leveraging the singleton object then please let me know so we can further review it.
That particular IP and path is for https://learn.microsoft.com/azure/virtual-machines/windows/instance-metadata-service?tabs=windows
The SDK is attempting to detect the Azure information. It could mean for Durable Functions, this information and endpoint is not available.
This does not affect SDK operations and should not block you from performing other actions on the CosmosClient instance.
I have HttpHandler (abc.ashx), which I make a call to process (Bulk Upload) an excel file. This processing takes a certain amount of time, which is proportionate to the number of rows in the excel.
On top of this I have an Event Handler in Sharepoint which uses a WebClient to make a post service call to this handler using the code below;
NOTE: I generate an identity token using elevated privilege of Sharepoint, and use that token to impersonate to make the service call. net net I make the post service call using the identity of the System Account.
WindowsIdentity identity = null;
// Get an identity token using delegate activity of Elevated Privelleges of Sharepoint
SPHelper.ElevatedActivity(properties.Web.Site.Url, properties.Web.ServerRelativeUrl, web =>
{
identity = WindowsIdentity.GetCurrent();
});
//Impersonates the identity of System Account user, as received in token in the line above
using (identity.Impersonate())
{
// create a web client object which only increases the timeout of the web client call
var webClient = (new CustomWebClient());
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
webClient.UseDefaultCredentials = true;
//url of the httphandler as deployed in sharepoint, and the parameters that needs to be passed
string handlerUrl =
string.Format(
properties.Web.Url.Trim('/') + "/_layouts/Handlers/abc.ashx?Table=BulkUpload&Region={0}&UserId={1}&BatchId={2}&FileUrl={3}",
region, userValue.User.LoginName, batchId, fileUrl);
}
// execute the web service call using the webclient object
webClient.DownloadString(handlerUrl));
Essentially this code is written in the Event Handler for ItemAdded and ItemUpdated event.
The issue is in the webClient which seems to give an error "system.net.webexception: the remote server returned an error: (401) unauthorized", after precisely 5 mins of processing. Hence if the excel sheet to be processed has rows less than certain number (1700), the processing happens within 5 minutes, and everything runs fine without any error. However if it has more than that, then the processing takes more than 5 minutes, and fails with the error specificed above.
The strange behaviour is it seems like a timeout issue but the error message indicates authorization issue, which does not make sense, as if there was an authorization issue, it shouldnt have worked even when the processing time was less that 5 minutes.
We have tried to find any configuration that times out in 5 minutes, however we could not find any.
Any help or suggestion on this matter is appreciated.
UPDATE: I have now tried to make this work using HttpWebRequest, and have tried a bunch of setting which might cause this timeout/issue. However still getting the same issue, where after 5 minutes of processing I am getting "system.net.webexception: the remote server returned an error: (401) unauthorized". Below is the code I have tried
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(handlerUrl);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.Timeout = 600000;
httpWebRequest.ReadWriteTimeout = 600000;
httpWebRequest.ServicePoint.ConnectionLeaseTimeout = 600000;
httpWebRequest.ServicePoint.MaxIdleTime = 600000;
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.ContentLength = 0;
httpWebRequest.Method = WebRequestMethods.Http.Get;
BulkUploadProcessorResponse response = null;
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream stream = httpWebResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
response =
JsonHelper.JsonDeserialize<BulkUploadProcessorResponse>(sr.ReadToEnd());
}
}
I have researched for days and not found an answer. I have used both google and Stack and MDSN so I finally thought it is time to ask the question. I am a new developer I completed my first assignment and my computer died. I got Win 8.1 pro and IIS 8.5 and now I am tasked with making that work with SQL 2012. I have it so I can load up the localhost to the first page of the app which is a login and then when I am debuging using Visual Studio after I start to log in
the first call to the db this comes up
An exception of type 'System.ServiceModel.ProtocolException' occurred in mscorlib.dll but was not handled in user code
Additional information: The remote server returned an unexpected response: (405) Method Not Allowed.
Then I get the same message again and then it sends me to the error page.
I am an IIS newbie, but I have ensured IUSER has the correct authorization and I have checked all of the web.configs, as well as the applicationHost file. This has to be a IIS problem is what I have come up but I would gladly be wrong if someone told me I was wrong and corrected. Thanks for the help.
Code Example
The first call to db where the first error pops up
MYapp.GlobalDataService.GlobalDataServiceClient gdc = new Myapp.Proxy.GlobalDataService.GlobalDataServiceClient();
ReadLogosResult result = gdc.GetLogos(_customerId, region_id, branch_id);
if (result != null)
{
logoContent = result.Logo;
}
This is after clicking login
public static int GetUserId(IIdentity contextIdentity)
{
FormsIdentity identity = contextIdentity as FormsIdentity;
if (identity == null)
{
throw new ApplicationException("cannot cast context identity to FormsIdentity type");
}
return Convert.ToInt32(identity.Ticket.UserData.Split(';')[0]);
}
Then this
for (int i = 0; i < ContextKeys.Length; i++)
{
string ContextKey = ContextKeys[i];
if (ContextKey == "appErr")
{
obj = (Exception)HttpContext.Current.Application["appErr"];
HttpContext.Current.Application.Remove("appErr");
}
if (ContextKey == "userId")
{
user = (int)HttpContext.Current.Application["userId"];
HttpContext.Current.Application.Remove("userId");
}
}
errors out Object reference not set to an instance of an object
then goes to our customer error page
I got it figured out. I needed to install HTTPActivation in WCF.
This is my first time ever with Sharepoint. Here is the scenario
I have a stand alone web application
I also have a stand alone sharepoint server.
Both are on different servers.
I need to upload a file from web application to sharepoint
I found 2 methods online,
Using the webservice provided by Sharepoint (CopyIntoItems)
Using jQuery library of Sharepoint webservice
After searching the web, I think the jQuery part will not work (you can correct me).
I am looking for a method that takes username/password and uploads a pdf file to Sharepoint server. The following is my C# code that tries to upload but ends up in error
public bool UploadFile(string file, string destination)
{
bool success = false;
CopySoapClient client = new CopySoapClient();
if (client.ClientCredentials != null)
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
try
{
client.Open();
string filename = Path.GetFileName(file);
string destinationUrl = destination + filename;
string[] destinationUrls = { destinationUrl };
FieldInformation i1 = new FieldInformation { DisplayName = "Title", InternalName = "Title", Type = FieldType.Text, Value = filename };
FieldInformation[] info = { i1 };
CopyResult[] result;
byte[] data = File.ReadAllBytes(file);
//uint ret = client.CopyIntoItems(filename, destinationUrls, info, data, out result);
uint ret = client.CopyIntoItems(file, destinationUrls, info, data, out result);
if (result != null && result.Length > 0 && result[0].ErrorCode == 0)
success = true;
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
client.Abort();
if (client.State != System.ServiceModel.CommunicationState.Closed)
client.Close();
}
return success;
}
I am calling the above function like this
UploadFile(#"C:\temp\uploadFile.txt", "http://spf-03:300/demo/Dokumente").ToString();
Error that i get:
Error Code: Destination Invalid
Error Message: The service method 'Copy' must be called on the same domain that contains the target URL.
There is the 3rd option with SharePoint 2010 and that is to use the Client Side object model. The client side object model a a sub set of the larger Sharepoint API, but it does cover uploading documents. Below is blog post with an example of uploading.
Upload document through client object model
As with most things in SharePoint you will need to authenticate against it the site, so find out if your site collection is forms based or claims based and then you should be able to find sample code for your situation.
Solution to the problem:
The problem was that the "security token webservice" was not working and it was giving some error when we manually ran the webservice.
The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
or from the configuration behavior) on the server in order to send the
exception information back to the client, or turn on tracing as per
the Microsoft .NET Framework 3.0 SDK documentation and inspect the
server trace logs.
The above exception is a generic one. To view the exact exception we enabled remote error viewing from the web.config file of the webservice(link) and saw the exact exception.
We found the solution for the exception and the service started. After that everything was working fine.
I'm trying to read a value from a list in a remote SharePoint site (different SP Web App). The web apps are set up with Claims Auth, and the client web app SP Managed account is configured with an SPN. I believe Kerberos and claims are set up correctly, but I am unable to reach the remote server, and the request causes an exception: "The remote server returned an error: (401) Unauthorized."
The exception occurs in the line ctx.ExecuteQuery(); but it does not catch the exception in the if (scope.HasException) instead, the exception is caught by the calling code (outside of the using{} block).
When I look at the traffic at the remote server using Wireshark, it doesn't look like the request is even getting to the server; it's almost as if the 401 occurs before the Kerberos ticket is exchanged for the claim.
Here's my code:
using (ClientContext ctx = new ClientContext(contextUrl))
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(contextUrl), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.Credentials = cc;
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
Web ctxWeb = ctx.Web;
List ctxList;
Microsoft.SharePoint.Client.ListItemCollection listItems;
using (scope.StartScope())
{
using (scope.StartTry())
{
ctxList = ctxWeb.Lists.GetByTitle("Reusable Content");
CamlQuery qry = new CamlQuery();
qry.ViewXml = string.Format(ViewQueryByField, "Title", "Text", SharedContentTitle);
listItems = ctxList.GetItems(qry);
ctx.Load(listItems, items => items.Include(
item => item["Title"],
item => item["ReusableHtml"],
item => item["ReusableText"]));
}
using (scope.StartCatch()) { }
using (scope.StartFinally()) { }
}
ctx.ExecuteQuery();
if (scope.HasException)
{
result = string.Format("Error retrieving content<!-- Error Message: {0} | {1} -->", scope.ErrorMessage, contextUrl);
}
if (listItems.Count == 1)
{
Microsoft.SharePoint.Client.ListItem contentItem = listItems[0];
if (SelectedType == SharedContentType.Html)
{
result = contentItem["ReusableHtml"].ToString();
}
else if (SelectedType == SharedContentType.Text)
{
result = contentItem["ReusableText"].ToString();
}
}
}
I realize the part with the CredentialCache shouldn't be necessary in claims, but every single example I can find is either running in a console app, or in a client side application of some kind; this code is running in the codebehind of a regular ASP.NET UserControl.
Edit: I should probably mention, the code above doesn't even work when the remote URL is the root site collection on the same web app as the calling code (which is in a site collection under /sites/)--in other words, even when the hostname is the same as the calling code.
Any suggestions of what to try next are greatly appreciated!
Mike
Is there a reason why you are not using the standard OM?
You already said this is running in a web part, which means it is in the context of application pool account. Unless you elevate permissions by switching users, it won't authenticate correctly. Maybe try that. But I would not use the client OM when you do have access to the API already.