Getting data from a Linq DbContext to a stored procedure - linq

I am calling a stored procedure using Linq. I want to put that data in list. Can anyone help me how to do this? You can see my code here:
public getidrange(int startrange, int endrange)
{
List<string> idRange = new List<string>();
string Conn = System.Configuration.ConfigurationManager.ConnectionStrings["mydbconnection"].ToString();
GetIDRangeDataContext GetIdRange = new GetIDRangeDataContext(Conn);
try
{
GetIdRange.sp_GetIdRange(startRange, endRange);
}
catch(Exception ex)
{
}
return idRange;
}

I just did the following to and it worked .
try
{
var res = GetIdRange.sp_GetIdRange(startRange, endRange);
foreach (var ids in res)
{
idRange.Add(ids.NewIDAnalisi.ToString());
objGetIdRangeResults.success = true;
}

Related

How check byte count (size) of existing blob (file) on Azure

I cannot find a decent example of how to use the latest version of Azure BlobClient to get the byte count of an existing blob.
Here is the code I am working with so far. I cannot figure out how to filter the blob I need to find. I can get them all, but it takes ages.
protected BlobContainerClient AzureBlobContainer
{
get
{
if (!isConfigurationLoaded) { throw new Exception("AzureCloud currently has no configuration loaded"); }
if (_azureBlobContainer == null)
{
if (!string.IsNullOrEmpty(_configuration.StorageEndpointConnection))
{
BlobServiceClient blobClient = new BlobServiceClient(_configuration.StorageEndpointConnection);
BlobContainerClient container = blobClient.GetBlobContainerClient(_configuration.StorageContainer);
container.CreateIfNotExists();
_azureBlobContainer = container;
}
}
return _azureBlobContainer;
}
}
public async Task<Response<BlobProperties>> GetAzureFileSize(string fileName)
{
BlobClient cloudFile = AzureBlobContainer.GetBlobClient(fileName);
await foreach (BlobItem blobItem in AzureBlobContainer.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
// Am i supposed to just iterate every single blob on there? how do I filter?
return blobProps;
}
Thoughts?
Ended up doing it like this... I get that it isn't the proper way, but it works.
public async Task<(BlobClient cloudFile, CopyFromUriOperation result)> MigrateFileToAzureBlobAsync(Uri url, string fileName, long? bytesCount)
{
BlobClient cloudFile = AzureBlobContainer.GetBlobClient(fileName);
cloudFile.DeleteIfExists();
BlobCopyFromUriOptions options = new BlobCopyFromUriOptions();
options.Metadata = new Dictionary<string, string>();
options.Metadata.Add("confexbytecount", bytesCount.ToString());
CopyFromUriOperation result = await cloudFile.StartCopyFromUriAsync(url, options);
Response x = await result.UpdateStatusAsync();
await result.WaitForCompletionAsync();
return (cloudFile, result);
}
public async Task<long> GetAzureFileSize(string fileName)
{
long retVal = 0;
await foreach (BlobItem blobItem in AzureBlobContainer.GetBlobsAsync(BlobTraits.All, BlobStates.All, fileName))
{
if (blobItem.Metadata.TryGetValue("confexbytecount", out string confexByteCount))
{
long.TryParse(confexByteCount, out retVal);
}
}
return retVal;
}

Parallel call to Elasticsearch in c#

I am trying to make a parallel call to Elasticsearch index for multiple queries and aggregate the result, using Parallel.ForEach.
My code:
private static List<SearchResponse<dynamic>> SearchQueryInParallel(string indexName, string lang, string[] eQueries)
{
var result = new List<SearchResponse<dynamic>>();
var exceptions = new ConcurrentQueue<Exception>();
object mutex = new object();
try
{
Parallel.ForEach(eQueries,
() => new SearchResponse<dynamic>()
, (q, loopState, subList) =>
{
var x = LowlevelClient.Search<SearchResponse<dynamic>>(indexName, $"article_{lang}", q);
subList = x;
return subList;
}, subList =>
{
lock (result)
result.Add(subList);
}
);
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
exceptions.Enqueue(e);
}
}
if (exceptions.ToList().Any())
{
//there are exceptions, do something with them
//do something?
}
return result;
}
The problem I am facing is that sublist in the above case is long.
It gives me the following error:
Can not convert from SearchResponse to long.
The same thing is working when I used without multithreading, the code is:
var items = new List<dynamic>();
var searchResponse = lowLevelClient.Search<SearchResponse<dynamic>>(elasticIndexName, $"article_{languageCode.ToLowerInvariant()}", query);
foreach (var document in searchResponse.Body.Documents)
{
items.Add(document);
}
Any help, please? If somebody has any other way to achieve the parallel call and aggregating data from returned values would be greatly appreciated.

TaskContinuation.cs not found exception while accessing WebAPI Task

I'm trying to fetch records from a db cursor from the Client app.
Debugging Web API shows that the Cursor returns records but when returning to the Client it throws mscorlib.pdb not loaded window and clicking on Load option it throws TaskContinuation.cs not found exception
Code snippets as below ( removed irrelevant codes for readability )
WebAPI
[HttpPost("{values}")]
public async Task<ActionResult> Post([FromBody] JToken values)
{
// code removed for readility
string[] cursors = { };
cursors = await cursor.GetRpts();
CursorClass firstCursor = JsonConvert.DeserializeObject<CursorClass>(cursors[0]);
return new OkObjectResult(cursors);
}
public async Task<string[]> GetRpts()
{
try
{
DataTable[] dataTables;
CursorClass[] cursorClasses = new CursorClass[5];
//stripped some code
using (DataAccess dataAccess = new DataAccess()
{
ParamData = PrepareDoc(),
ProcedureName = Constants.Rpt,
RecordSets = this.CursorNumbers,
})
{
Int32 errorNumber = await dataAccess.RunComAsync();
dataTables = dataAccess.TableData;
};
//fetching code stripped off
string[] _cursors = Array.ConvertAll(cursorClasses, JsonConvert.SerializeObject);
return _cursors;
}
catch (Exception ex)
{
string tt = ex.Message;
}
}
public async Task<Int32> RunComAsync()
{
Int32 returnValue = 0;
try
{
//open db connection
//---------- Running the Command in asysnc mode ----------
Task<int> task = new Task<int>(oracleCommand.ExecuteNonQuery);
task.Start();
returnValue = await task;
//--------------------------------------------------------
OracleRefCursor[] refCursor = { null, null, null, null, null };
for (int _sub = 0; _sub < RecordSets; _sub++)
{
//DT declaration / connection code removed
dataAdapter.Fill(dataTable, refCursor[_sub]);
TableData[_sub] = dataTable;
}
}
catch (Exception ex)
{
return LogMsg(ex);
}
finally
{
this.Dispose(true);
}
CloseConnection();
return LogMsg(null,"Successful Operation");
}
Client
private async Task<HttpStatusCode> CallService()
{
HttpResponseMessage _response = null;
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JsonRepo, System.Text.Encoding.UTF8, HeaderJson),
RequestUri = new Uri(UriString),
Method = HttpMethod.Post,
})
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.TOKEN) ;
_response = await httpClient.SendAsync(requestMessage);
if (_response.IsSuccessStatusCode)
{
string httpResponse = await _response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
}
}
return ErrorCode;
}
Is that something related to async operation? while debugging the API it confirms the Datatable with records . Any inputs are deeply appreciated.
error image
TIA

How to roll back queries in C#?

I have list of delete queries & I execute them with this code:
using (var ctx = new ApplicationDbContext(schemaName))
{
foreach (var item in queries)
{
ctx.Database.ExecuteSqlCommand(item);
}
}
I want to commit all the delete queries, but I want to roll back if there is some error in any of the queries.
How to do roll back in the above scenario?
Try to use TransactionScope
using System.Transactions;
try
{
using (var scope = new TransactionScope())
{
using (var ctx = new ApplicationDbContext(schemaName))
{
foreach (var item in queries)
{
ctx.Database.ExecuteSqlCommand(item);
}
}
scope.Complete();
}
}
catch (Exception ex)
{
}

Get the Readable Message from ManagementObject.InvokeMethod

Is there any way to get the Message Text from the return value of WMI InvokeMethod e.g. for the following code
ManagementBaseObject outParam = nicMO.InvokeMethod("SetGateways", newGateway, null);
int result = outParam["ReturnValue"];
Microsoft has published return values
Is there anyway to get the readable message from the return values instead creating hardcoded return value and message dictionary.
note: Please give me something which can work in .net 2.0 (and/or .net 1.1)
You can get the description of the value returned by the SetGateWays method using the ValueMap and Value Qualifiers .
Try this sample
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<String> LValues = new List<String>();
List<String> LValuesDesc = new List<String>();
Dictionary<String, String> LValuesDict = new Dictionary<String, String>();
ManagementClass WClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
WClass.Options.UseAmendedQualifiers = true;
foreach (MethodData md in WClass.Methods)
{
if (md.Name.Equals("SetGateways"))
{
//fill a list with the ValuesMap
foreach (QualifierData q in md.Qualifiers)
{
if (q.Name.Equals("ValueMap"))
{
foreach (object Value in ((Array)q.Value))
{
LValues.Add(Convert.ToString(Value));
}
}
}
//fill a list with the Values
foreach (QualifierData q in md.Qualifiers)
{
if (q.Name.Equals("Values"))
{
foreach (object Value in ((Array)q.Value))
{
LValuesDesc.Add(Convert.ToString(Value));
}
}
}
//Merge both lists in a dictionary
for (int i = 0; i <= LValues.Count - 1; i++)
LValuesDict.Add(LValues[i], LValuesDesc[i]);
}
}
//Get the description of some return values
Console.WriteLine(LValuesDict["1"]);
Console.WriteLine(LValuesDict["64"]);
Console.WriteLine(LValuesDict["77"]);
Console.WriteLine(LValuesDict["91"]);
Console.ReadKey();
}
}
}

Resources