I am writing an asp.net web API using Visual Studio 2019. When I write as in the example below, Visual Studio recommends me making the method static. So I followed the suggestions and made all methods of the Web API static. Is this correct? What is the advantage if it is correct and what is the disadvantage if it is wrong?
Thank you...
Severity Code Description Project File Line Suppression State
Message CA1822 Member AdresleriGetir does not access instance data and can be marked as static (Shared in VisualBasic) Devriye.WebApi**
My method:
[HttpPost]
public static Adres[] AdresleriGetir([FromBody]GirisParametresi girisParametresi)
{
if (girisParametresi != null)
{
string query = #"SELECT * FROM ADRESLER WHERE AKTIF=1";
Cagri cagri = new Cagri()
{
Proje = "Devriye.WebApi",
Modul = "AdresController",
Metot = "AdresGetir",
Nesne = new JavaScriptSerializer().Serialize(girisParametresi)
};
Log log = new Log(null, cagri, girisParametresi.Oturum);
using (DataTable dataTable = DataAccessLayer.VerileriGetir(query, null, log))
{
List<Adres> adresler = new List<Adres>();
if (dataTable.Rows.Count > 0)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Adres adres = new Adres();
try { adres.Cadde = Convert.ToString(dataTable.Rows[i]["Cadde".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.EklenmeTarihi = Convert.ToDateTime(dataTable.Rows[i]["EklenmeTarihi".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.ID = Convert.ToInt32(dataTable.Rows[i]["ID".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Il = Convert.ToString(dataTable.Rows[i]["Il".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Ilce = Convert.ToString(dataTable.Rows[i]["Ilce".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.KapiNo = Convert.ToString(dataTable.Rows[i]["KapiNo".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Mahalle = Convert.ToString(dataTable.Rows[i]["Mahalle".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.PostaKodu = Convert.ToInt32(dataTable.Rows[i]["PostaKodu".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Sokak = Convert.ToString(dataTable.Rows[i]["Sokak".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
adresler.Add(adres);
}
return adresler.ToArray();
}
else
{
return null;
}
}
}
else
{
return null;
}
}
This function doesn't access any instance data or call any instance methods.
I've had similar questions about R# wanting to convert this type of function to static. See this SO question for some reasons. From the accepted answer in the link;
It makes me ask myself if the method in question should actually be
part of the type or not. Since it doesn't use any instance data, you
should at least consider if it could be moved to its own type. Is it
an integral part of the type, or is it really a general purpose
utility method?
If it does make sense to keep the method on the specific type, there's
a potential performance gain as the compiler will emit different code
for a static method.
Related
I am trying to Get EventMessage from Message in MS Graph API with C# but every time it is showing type as a message instead of EventMessage. Below are the code:-
public static Graph.MailFolderMessagesCollectionPage ReadInbox()
{
GetAuthenticatedClient();
var result = new Graph.MailFolderMessagesCollectionPage();
List<Graph.QueryOption> options = new List<Graph.QueryOption>
{
new Graph.QueryOption("$expand","microsoft.graph.eventMessage/event"),
new Graph.QueryOption("$filter","isread eq false")
};
try
{
var response = graphClient.Me.MailFolders.Inbox.Messages.Request(options).OrderBy("receivedDateTime DESC").GetAsync();
result = response.Result as Graph.MailFolderMessagesCollectionPage;
}
catch (Exception ex)
{ }
Call the above method ReadInbox to get type and perform some action.
var appointments = ReadInbox();
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (request.GetType().Name.Contains("EventMessage"))
{
}
else if (request.GetType().Name == "Message")
{
}
}
catch (Exception ex)
{
}
}
}
Use the IsInstanceOfType method to identify if its an eventMessage. You can also remove the expand option from the query option since eventMessages are fetched anyway as part of the get Messages call.
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (typeof(EventMessage).IsInstanceOfType(request))
{
Console.WriteLine("Is an event");
Console.WriteLine(request);
}
}
catch (Exception ex)
{
}
}
}
I am running my .net core 3.0 application in ubuntu 18.04 machine in same network where redis present
I am getting error
Timeout performing ZADD (10000ms), next: HSCAN InProccessingMsisdnTransaction_34234234, inst: 1, qu: 0, qs: 81, aw: False, rs: ReadAsync, ws: Idle, in: 34117, in-pipe: 0, out-pipe: 0, serverEndpoint: 10.10.10.10:6379, mgr: 10 of 10 available, clientName: SafeRedisConnection, IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=32,Free=32735,Min=2,Max=32767), v: 2.0.601.3402 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts)
My implementation for redis interaction is as following
public static class RedisManager
{
private static readonly bool LogRedisRelatedActivities;
private static readonly Lazy<ConfigurationOptions> ConfigOptions = new Lazy<ConfigurationOptions>(() =>
{
ConfigurationOptions configOptions = null;
try
{
var redisInfo = ConfigurationHandler.GetSection<RedisElement>("RedisSection");
if (redisInfo != null )
{
if (redisInfo.IsActive)
{
redisInfo.RedisServerNameOrIp = ConfigurationHandler.GetSection<string>(StringConstants.EnvConfig.RedisRedisServerNameOrIp, Configurationtype.RedisSection);
redisInfo.RedisServerPort = ConfigurationHandler.GetSection<string>(StringConstants.EnvConfig.RedisRedisServerPort, Configurationtype.RedisSection);
redisInfo.RedisDefaultDatabase = ConfigurationHandler.GetSection<int>(StringConstants.EnvConfig.RedisDefaultDatabase, Configurationtype.RedisSection);
configOptions = new ConfigurationOptions();
configOptions.EndPoints.Add(redisInfo.RedisServerNameOrIp + ":" + redisInfo.RedisServerPort);
configOptions.ClientName = "SafeRedisConnection";
configOptions.ConnectTimeout = redisInfo.ConnectTimeout * 1000;
configOptions.SyncTimeout = redisInfo.SyncTimeout * 1000;
configOptions.AbortOnConnectFail = false;
configOptions.KeepAlive = redisInfo.KeepAliveDuration;
configOptions.DefaultDatabase = redisInfo.RedisDefaultDatabase;
}
else
{
Logger.Error("RedisSection is in-active");
}
}
else
{
Logger.Error("RedisSection not found");
}
}
catch (Exception ex)
{
Logger.Fatal(ex, ex);
}
return configOptions;
});
private static readonly Lazy<ConnectionMultiplexer> Conn = new Lazy<ConnectionMultiplexer>(
() =>
{
try
{
if (ConfigOptions != null && ConfigOptions.Value != null)
{
return ConnectionMultiplexer.Connect(ConfigOptions.Value);
}
return null;
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
return null;
}
});
private static ConnectionMultiplexer Muxer => Conn.Value;
static RedisManager()
{
try
{
LogRedisRelatedActivities = ConfigurationHandler.GetSection<bool>(StringConstants.AppSettingsKeys.LogRedisRelatedActivities);
if (Muxer != null && Muxer.IsConnected)
{
Logger.Info("Redis Connected ");
}
else
{
Logger.Info("Redis Not Connected ");
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
}
public static string GetStringItem(string key)
{
string val = null;
try
{
IDatabase getDatabase;
if (Muxer != null && Muxer.IsConnected && (getDatabase = Muxer.GetDatabase()) != null)
{
val = getDatabase.StringGet(key);
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
return val;
}
public static bool AddZList(string key, object value)
{
var isAdded = false;
try
{
IDatabase getDatabase;
if (Muxer != null && Muxer.IsConnected && (getDatabase = Muxer.GetDatabase()) != null)
{
isAdded = getDatabase.SortedSetAdd(key, JsonSerializer.Serialize(value), Utility.GetCurrentSystemTime().Ticks);
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
return isAdded;
}
}
When running same application from windows server i am not getting any such error
Problem was related to some threadpool implemenation in stackexchange.redis.
Workaround is to initialize high number of minimum thread in our application. done it via some configuration in .csproj file
I have a series of asynchronous functions that are cascaded, but when it finishes executing the last, it does not return the values to the previous ones.
This is where my first call is run. This is a WebAPI function and always comes to an end.
[HttpGet]
[Route("integracao/iniciar")]
public IHttpActionResult FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
so my function is in my library is called. Within my function I have a for executing only once. The flow is never resumed by it to continue the loop
public async Task<bool> Integra()
{
var files = Directory.GetFiles(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\");
bool retorno = false;
if (files != null)
{
foreach (var item in files)
{
retorno = false;
using (StreamReader sr = new StreamReader(item))
{
if (sr != null)
{
while (sr.EndOfStream == false)
{
string line = await sr.ReadLineAsync();
string[] grupo = line.Split(new[] { "#*#" }, StringSplitOptions.None);
procData objProc = new procData();
objProc.proc = grupo[0];
objProc.name = JsonConvert.DeserializeObject<List<string>>(grupo[1]);
objProc.valor = JsonConvert.DeserializeObject<List<object>>(grupo[2]);
objProc.tipo = JsonConvert.DeserializeObject<List<Type>>(grupo[3]);
_context = new IntegrarRepository("online_pedidopizza");
retorno = await _context.IntegrarAsync(objProc);
//retorno = await _context.IntegrarAsync(objProc);
}
}
}
if (retorno == true)
{
await DeleteAsync(item);
}
}
}
return retorno;
}
I have a third function just to mediate with the repository
public async Task<bool> IntegrarAsync(procData objProc)
{
return await this.SendIntegrarAsync(objProc);
}
And finally, communication with the database, all code is executed correctly. Debugging you can get to the end of this fourth function but then the debug stop and does not go back to the beginning
protected async Task<bool> SendIntegrarAsync(procData parametro)
{
bool retorno = false;
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand cmd = new SqlCommand(parametro.proc, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parametro != null)
{
for (int i = 0; i < parametro.name.Count; i++)
{
AdicionaParametro(cmd, parametro.name[i], parametro.valor[i], parametro.tipo[i]);
}
}
try
{
cmd.CommandTimeout = 300;
await conn.OpenAsync().ConfigureAwait(false);
var resultado = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
if (resultado != null)
{
retorno = Convert.ToBoolean(resultado);
}
}
catch (Exception ex)
{
Logs objLog = new Logs()
{
metodo = MethodBase.GetCurrentMethod().Name,
classe = this.GetType().Name,
dados = parametro,
data = DateTime.Now,
mensagem = ex.Message,
exception = ex.InnerException == null ? "" : ex.InnerException.ToString()
};
objLog.Adiciona();
string name = DateTime.Now.ToBinary().ToString();
using (StreamWriter sw = new StreamWriter(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\" + name + ".txt"))
{
string line = "";
line += parametro.proc + "#*#";
line += JsonConvert.SerializeObject(parametro.name) + "#*#";
line += JsonConvert.SerializeObject(parametro.valor) + "#*#";
line += JsonConvert.SerializeObject(parametro.tipo) + "#*#";
sw.WriteLine(line);
}
}
}
}
return retorno;
}
What should I have to do? Thanks
Your Web Api call is not async try changing it to:
[HttpGet]
[Route("integracao/iniciar")]
public async Task<IHttpActionResult> FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(await objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
I am trying to create functionality to copy data from one order to another. Here is the code that copies the data:
protected void copySeminarIDButton_Click(object sender, EventArgs e)
{
try
{
//show some message incase validation failed and return
String seminarID = this.copySeminarIDText.Text;
Int32 id;
try
{
id = Convert.ToInt32(seminarID);
} catch (Exception e2)
{
return;
}
//copy over all the registration types now for the entered id
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
var seminars = db.seminars.Where(x => x.id == id);
if (seminars.Any())
{
var s = seminars.First();
//Load RegTypes
try
{
var regList = s.seminar_registration_type
.OrderBy(x => x.sort)
.ToList()
.Select(x => new seminarRegistrationTypeListing
{
id = x.id,
amount = x.amount,
description = x.description,
feeTypeId = x.feeTypeId,
method = x.method,
promoCodes = PromoCodesToString(x.xref_reg_type_promo.Select(z => z.promoId).ToList()),
title = x.title,
isPreorder = x.isPreorder,
sort = x.sort
});
this.dlTypes.DataSource = regList;
this.dlTypes.DataBind();
}
catch (Exception ex)
{
Response.Write("RegTypes: " + ex.Message);
}
} else
{
return;
}
}
}
catch (Exception m)
{
}
}
The user will enter a ID of the invoice they want to copy from. The above code copies pull the right data from the invoice and loads it on the page. When i click save the data is being saved.
The problem that is occurring is that the invoice that i copy data from will no longer have the data any more. So basically instead of copying the data its actually moving the data to the new invoice. I want to copy.
Here is my Save code.
private void SaveRegTypes(int seminarId)
{
//Reg Types
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
try
{
var s = db.seminars.Where(x => x.id == seminarId).First();
var msg = "alert('Saving:" + seminarId + "');";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", msg, true);
this.copySeminarIDText.Text = msg;
//s.seminar_registration_type.Clear();
foreach (DataListItem dli in this.dlTypes.Items)
{
String sId = ((HiddenField)dli.FindControl("hdnId")).Value;
var reg = new seminar_registration_type();
if ((sId != "") && (sId != "0"))
{
Int32 id = Convert.ToInt32(sId);
reg = db.seminar_registration_type.Where(x => x.id == id).Single();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", "alert('hidded field id is empty.');", true);
}
else
{
db.seminar_registration_type.Add(reg);
}
reg.feeTypeId = Convert.ToInt32(((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Value);
reg.amount = Convert.ToDecimal(((TextBox)dli.FindControl("txtPrice")).Text);
reg.title = ((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Text;
reg.description = ((TextBox)dli.FindControl("txtRegDesc")).Text;
reg.method = Convert.ToInt32(((DropDownList)dli.FindControl("ddlDeliveryMethod")).Text);
reg.promocode = null;
reg.isPreorder = Convert.ToBoolean(((CheckBox)dli.FindControl("chkPreorder")).Checked);
reg.sort = 1;
reg.seminarId = seminarId;
string sort = ((TextBox)dli.FindControl("txtRTSort")).Text;
try
{
reg.sort = Convert.ToInt32(sort);
}
catch (Exception ex) { }
//Do Promo Codes
Repeater rptPromocodes = (Repeater)dli.FindControl("rptPromoCodesList");
reg.xref_reg_type_promo.Clear();
foreach (RepeaterItem ri in rptPromocodes.Items)
{
try
{
Int32 id = Convert.ToInt32(((HiddenField)ri.FindControl("hdnCodeId")).Value);
DateTime? expires = null;
try
{
HiddenField exp = (HiddenField)ri.FindControl("hdnExpirationDate");
if (!String.IsNullOrWhiteSpace(exp.Value))
expires = Convert.ToDateTime(((HiddenField)ri.FindControl("hdnExpirationDate")).Value);
}
catch (Exception ex) { }
var code = db.promo_code.Where(x => x.id == id).First();
reg.xref_reg_type_promo.Add(new xref_reg_type_promo
{
expiration = expires,
promoId = code.id
});
}
catch (Exception ex) { }
}
db.SaveChanges();
((HiddenField)dli.FindControl("hdnId")).Value = reg.id.ToString();
}
}
catch (Exception ex)
{
String err = ex.Message;
}
}
}
I use following script to get data from external service and store in dB. In certain rare cases less than 1% records gets updated with null values. In below code, the "re.status=fail" we see null. let us know if any thots.
public void ProcessEnquiries()
{
List<req> request = new List<req>();
var options = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxDegreeOfParallelism"]) };
try
{
Parallel.ForEach(request, options, currentRequest =>
{
ProcessedRequest processedRequest = null;
processedRequest = CommunicateToWS(currentRequest); // Here we call to webservice
});
}
catch (AggregateException exception)
{
foreach (Exception ex in exception.InnerExceptions)
{
// Handle Exception
}
}
}
public ProcessedRequest CommunicateToWS(req objReq)
{
ProcessedRequest re = new ProcessedRequest();
using (WebCall obj = new WebCall())
{
re.no = refnu;
try
{
retval = obj.getValue(inval);
objProxy.Close();
//get data
// parse and store to DB
}
catch (Exception e)
{
re.status = "fail";
//update DB that request has failed
//Handle Exception
obj.Close();
}
}
}