I am creating a method for checking the product key. everything working fine in bltoolkit the code is
private void CheckKey()
{
try
{
using (DbManager db = new DbManager())
{
DataTable dt = db
.SetCommand("SELECT TOP 1 * FROM TblReg WHERE ProductKey=#ProductKey",
db.Parameter("#ProductKey", CommanClass.strRegkey))
.ExecuteDataTable();
if (dt.Rows.Count == 0)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = dt.Rows[0].Field<string>("ProductKey");
GetSoftKey = true;
}
}
if ((GetSoftKey == true) && (strSoftKey != null))
{
if (strSoftKey == CommanClass.strRegkey)
{
SoftwareKey = true;
}
else
{
SoftwareKey = false;
}
}
}
catch (Exception)
{
SoftwareKey = false;
}
}
Now in When I try to write a method using entity framework for checking product key, it's confusing me at how to pass DataTable variable DataTable dt = login into entity context and set entity query parameter login.Parameter("#ProductKey", CommanClass.strRegkey), the code is
private void CheckKey()
{
try
{
using (loginEntities login = new loginEntities())
{
var pKey= from pk in login.tblSoftRegs
where pk.ProductKey == pk.ProductKey
select pk.ProductKey.FirstOrDefault();
if (pKey.Count() == 0)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = ("ProductKey");
GetSoftKey = true;
}
}
if ((GetSoftKey == true) && (strSoftKey != null))
{
if (strSoftKey == CommanClass.busRegkey)
{
SoftwareKey = true;
}
else
{
SoftwareKey = false;
}
}
}
catch (Exception)
{
SoftwareKey = false;
}
}
Waiting for community contribution...
You've almost got it. FirstOrDefault will return null if there are none found, and you bind local variables directly into your LINQ query. Like this:
var pKey= from pk in login.tblSoftRegs
where pk.ProductKey == CommanClass.strRegkey
select pk.ProductKey.FirstOrDefault();
if (pKey == null)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = ("ProductKey");
GetSoftKey = true;
}
Related
so i have this code:
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Net.Http.Headers;
using Roblox.Libraries.EasyJwt;
using Roblox.Libraries.Password;
using Roblox.Logging;
using Roblox.Models.Sessions;
using Roblox.Services.App.FeatureFlags;
using Roblox.Website.Controllers;
using Roblox.Website.Lib;
namespace Roblox.Website.Middleware;
public class ApplicationGuardMiddleware
{
private static string authorization { get; set; }
public const string AuthorizationHeaderName = "rblx-authorization";
public const string AuthorizationCookieName = "rblx-authorization";
public static List<string> allowedUrls { get; } = new()
{
"/auth/captcha",
"/auth/discord",
"/auth/submit",
"/auth/home",
"/auth/privacy",
"/auth/tos",
"/auth/login",
"/auth/password-reset",
"/auth/contact",
"/auth/account-deletion",
"/auth/application",
"/auth/signup",
"/auth/ticket",
"/auth/application-check",
// razor public
"/unsecuredcontent/",
// gs
"/gs/activity",
"/gs/ping",
"/gs/delete",
"/gs/shutdown",
"/gs/players/report",
"/gs/a",
// other
"/game/validate-machine",
"/game/validateticket.ashx",
"/game/get-join-script-debug",
"/api/moderation/filtertext"
};
public static void Configure(string authorizationString)
{
authorization = authorizationString;
}
public static string GetKey()
{
return authorization;
}
private RequestDelegate _next { get; set; }
public ApplicationGuardMiddleware(RequestDelegate next)
{
_next = next;
}
private bool IsAuthorized(HttpContext ctx)
{
if (ctx.Request.Headers.ContainsKey(AuthorizationHeaderName))
{
return ctx.Request.Headers[AuthorizationHeaderName].ToArray()[0] == authorization;
}
if (ctx.Request.Cookies.ContainsKey(AuthorizationCookieName))
{
// return ctx.Request.Cookies[AuthorizationCookieName]?.Contains(authorization) ?? false;
}
if (ctx.Items.ContainsKey(".ROBLOSECURITY"))
return true;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
private static bool IsOldBrowser(string ua)
{
// this is mostly to stop bots using ancient user agents, which is (strangely) incredibly common
const int minVersionChrome = 70; // todo: increase to 81
// https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome
const int minVersionFirefox = 70; // todo: increase to 78
// https://www.whatismybrowser.com/guides/the-latest-user-agent/firefox
const int minVersionSafari = 602; // we actually use the WebKit version here
// https://www.whatismybrowser.com/guides/the-latest-user-agent/safari
if (ua.Contains("chrome/"))
{
for (var i = 0; i < minVersionChrome; i++)
{
if (ua.Contains("chrome/" + i + "."))
return true;
}
}
else if (ua.Contains("firefox/"))
{
for (var i = 0; i < minVersionFirefox; i++)
{
if (ua.Contains("firefox/" + i + "."))
return true;
}
}
else if (ua.Contains("safari/"))
{
for (var i = 0; i < minVersionSafari; i++)
{
if (ua.Contains("safari/" + i + "."))
return true;
}
}
return false;
}
[SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
[MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
private bool IsUserAgentBlocked(string ua)
{
// note that this isn't really for blocking malicious actors, it's just for preventing search engines (and
// similar services) from crawling our site
ua = ua.ToLower().Trim();
if (string.IsNullOrWhiteSpace(ua)) return true;
// Google Crawlers
// please keep this up-to-date with https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
if (ua.IndexOf("apis-google") != -1) return true;
if (ua.IndexOf("mediapartners-google") != -1) return true;
if (ua.IndexOf("adsbot-google") != -1) return true; // adsbot-google, adsbot-google-mobile, adsbot-google-Mobile-Apps
if (ua.IndexOf("googlebot") != -1) return true; // Googlebot, Googlebot-Image, Googlebot-News, Googlebot-Video
if (ua.IndexOf("feedfetcher-google") != -1) return true;
if (ua.IndexOf("google-read-aloud") != -1) return true;
if (ua.IndexOf("duplexweb-google") != -1) return true;
if (ua.IndexOf("storebot-google") != -1) return true;
if (ua.IndexOf("google-site-verification") != -1) return true; // https://www.google.com/webmasters/tools/verification/google-site-verification.html
if (ua == "google") return true; // sometimes the ua is literally just "google"? wtf
// todo: do we block "Google Favicon"?
// todo: do we block "googleweblight"?
// Bing Crawlers
// please keep this up-to-date with https://www.bing.com/webmasters/help/which-crawlers-does-bing-use-8c184ec0
if (ua.IndexOf("bingbot") != -1) return true;
if (ua.IndexOf("adidxbot") != -1) return true;
if (ua.IndexOf("bingpreview") != -1) return true;
// Yahoo Crawlers
// please keep this up-to-date with https://help.yahoo.com/kb/SLN22600.html
if (ua.IndexOf("yahoo! slurp") != -1) return true;
// Facebook (meta) Crawlers
// please keep this up-to-date with https://developers.facebook.com/docs/sharing/webmasters/crawler/
if (ua.IndexOf("facebookexternalhit") != -1) return true;
// Other crawlers
if (ua.IndexOf("qwantify") != -1) return true;
if (ua.IndexOf("duckduckgo") != -1) return true;
// Old browsers
// Even if they were legitimate users, they probably wouldn't be able to use the site due to the ssl certs being
// too new, and even if they could visit the site, it wouldn't even load properly.
if (IsOldBrowser(ua)) return true;
if (ua == "chrome") return true; // todo: what is this?
if (ua == "firefox") return true; // todo: what is this?
if (ua == "safari") return true; // todo: what is this?
if (ua == "opera") return true; // todo: what is this?
// Misc
// From https://developers.whatismybrowser.com/useragents/explore/software_type_specific/crawler/
if (ua.IndexOf("baiduspider") != -1) return true;
if (ua.IndexOf("mj12bot") != -1) return true; // https://majestic.com/
if (ua.IndexOf("megaindex") != -1) return true;
if (ua.IndexOf("ahrefsbot") != -1) return true;
if (ua.IndexOf("semrushbot") != -1) return true;
if (ua.IndexOf("dotbot") != -1) return true;
if (ua.IndexOf("jobboersebot") != -1) return true;
if (ua.IndexOf("yandexbot") != -1) return true;
if (ua.IndexOf("yandex.com") != -1) return true;
if (ua.IndexOf("developers.google.com") != -1) return true; // https://developers.whatismybrowser.com/useragents/parse/464220google-snippet-fetcher
if (ua.IndexOf("msnbot") != -1) return true; // msn is still around???
if (ua.IndexOf("seoscanners.net") != -1) return true;
if (ua.IndexOf("seokicks") != -1) return true;
if (ua.IndexOf("petalbot") != -1) return true;
if (ua.IndexOf("ia_archiver") != -1) return true; // archive.org
if (ua.IndexOf("censys") != -1) return true;
if (ua.IndexOf("paloaltonetworks") != -1) return true;
if (ua.IndexOf("alittle client") != -1) return true;
if (ua.IndexOf("webmeup-crawler.com") != -1) return true;
if (ua.IndexOf("blexbot") != -1) return true;
if (ua.IndexOf("turnitinbot") != -1) return true; // http://www.turnitin.com/robot/crawlerinfo.html
if (ua.IndexOf("npbot") != -1) return true; // http://www.nameprotect.com/botinfo.html
if (ua.IndexOf("slysearch") != -1) return true; // http://www.slysearch.com/
if (ua.IndexOf("spaziodati.eu") != -1) return true;
if (ua.IndexOf("ezgif.com") != -1) return true;
if (ua.IndexOf("archive.org") != -1) return true;
if (ua.IndexOf("iframely") != -1) return true;
if (ua.IndexOf("googlesites") != -1) return true;
if (ua.IndexOf("comscore.com") != -1) return true; // https://www.comscore.com/Web-Crawler
if (ua.IndexOf("proximic.com") != -1) return true; // http://www.proximic.com/info/spider.php
if (ua.IndexOf("opengraph.io") != -1) return true; // https://opengraph.io/
if (ua.IndexOf("roblox.com") != -1) return true; // todo: what is this?
if (ua.IndexOf("seznambot") != -1) return true; // https://napoveda.seznam.cz/en/seznamcz-web-search/
if (ua.IndexOf("headline.com") != -1) return true; // https://www.headline.com/
if (ua.IndexOf("ev-crawler") != -1) return true; // https://www.headline.com/
if (ua.IndexOf("crawler4j") != -1) return true; // https://crawler4j.github.io/crawler4j/
if (ua.IndexOf("api.slack.com") != -1) return true; // https://api.slack.com/robots.txt
if (ua.IndexOf("slackbot") != -1) return true; // https://api.slack.com/robots.txt
if (ua.IndexOf("slack-img") != -1) return true; // https://api.slack.com/robots.txt
if (ua.IndexOf("slack-screenshot") != -1) return true; // https://api.slack.com/robots.txt
if (ua.IndexOf("slack-ss") != -1) return true; // https://api.slack.com/robots.txt
// languages (if you get blocked, do NOT uncomment these, just change your UA to something descriptive
// (e.g. "AvatarRender/1.0")
if (ua.IndexOf("python-requests") != -1) return true;
if (ua.IndexOf("go-http-client") != -1) return true;
if (ua.IndexOf("axios") != -1) return true;
if (ua.IndexOf("node-fetch") != -1) return true;
if (ua.IndexOf("node-request") != -1) return true;
if (ua.IndexOf("node-http") != -1) return true;
if (ua.IndexOf("node-https") != -1) return true;
if (ua.IndexOf("grequests") != -1) return true;
if (ua.IndexOf("http-client") != -1) return true;
if (ua.IndexOf("github.com") != -1) return true; // e.g. "github.com/sindresorhus/got"
if (ua.IndexOf("gitlab.com") != -1) return true;
if (ua.IndexOf("bitbucket.org") != -1) return true;
if (ua.IndexOf("bitbucket.com") != -1) return true;
if (ua.IndexOf("githubusercontent.com") != -1) return true;
if (ua.IndexOf("github.io") != -1) return true;
if (ua == "ruby") return true;
if (ua.IndexOf("test certificate info") != -1) return true;
if (ua == "wp_is_mobile") return true; // no clue what this is
if (ua.IndexOf("curl/") != -1) return true;
if (ua.IndexOf("wget/") != -1) return true;
if (ua.IndexOf("well-known.dev") != -1) return true;
if (ua == "aids") return true; // ?
return false;
}
private readonly string[] allowedPathsForBlockUserAgents = new[]
{
"",
"/auth/home",
"/auth/captcha",
};
private async Task Redirect(HttpContext ctx, string dest)
{
ctx.Response.StatusCode = 302;
ctx.Response.Headers.Location = "/auth/home";
await ctx.Response.WriteAsync("Object moved to here.");
}
public async Task InvokeAsync(HttpContext ctx)
{
var appGuardTimer = new MiddlewareTimer(ctx, "AppGuard");
var normalizedPath = ctx.Request.Path.Value?.ToLower() ?? "";
if (normalizedPath.EndsWith("/"))
{
normalizedPath = normalizedPath.Substring(0, normalizedPath.Length - 1);
}
if (normalizedPath == "/robots.txt")
{
var created = DateTime.UtcNow.ToString("O");
var disallow = new List<string>()
{
"/My/*",
"/Games/*",
"/Users/*",
"/Catalog",
"/Catalog/*",
"/Forum",
"/Forum/*",
"/Internal/*",
};
var newItems = new List<string>();
foreach (var item in disallow)
{
newItems.Add(item.ToLower());
}
newItems.ForEach(v => disallow.Add(v));
ctx.Response.Headers.ContentType = "text/plain";
ctx.Response.Headers.CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromHours(24),
}.ToString();
await ctx.Response.WriteAsync("user-agent: *\n\n" + string.Join("\n", disallow.Select(c => "disallow: " + c)) + "\n\n#" + created);
return;
}
var uaTimer = new MiddlewareTimer(ctx, "ua");
var ua = ctx.Request.Headers["user-agent"].ToString();
var uaBlocked = IsUserAgentBlocked(ua);
var bypassOk = false;
var bypassAllowedForPath = allowedPathsForBlockUserAgents.Contains(normalizedPath);
if (uaBlocked && !bypassAllowedForPath)
{
var uaBypassWatch = new Stopwatch();
uaBypassWatch.Start();
if (ctx.Request.Cookies.TryGetValue("uabypass1", out var cookieBypass) && !string.IsNullOrWhiteSpace(cookieBypass))
{
var deleteCookie = false;
try
{
var jwtService = new EasyJwt();
var result =
jwtService.DecodeJwt<UserAgentBypass>(cookieBypass, Roblox.Configuration.UserAgentBypassSecret);
if (result.createdAt > DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) &&
result.userAgent == ctx.Request.Headers.UserAgent)
{
var ipHash = ControllerBase.GetIP(ControllerBase.GetRequesterIpRaw(ctx), result.GetSalt());
if (result.ipAddress == ipHash)
{
uaBlocked = false;
bypassOk = true;
}
else
{
deleteCookie = true;
}
}
else
{
deleteCookie = true;
}
}
catch (Exception e)
{
deleteCookie = true;
Writer.Info(LogGroup.AbuseDetection, "Error while decoding UA bypass: " + e.Message);
}
if (deleteCookie)
ctx.Response.Cookies.Delete("uabypass1");
}
uaBypassWatch.Stop();
Writer.Info(LogGroup.AbuseDetection, "took {0}ms to parse ua bypass cookie", uaBypassWatch.ElapsedMilliseconds);
}
if (uaBlocked && !bypassAllowedForPath)
{
ctx.Response.StatusCode = 302;
ctx.Response.Headers.ContentType = "text/html; charset=utf-8";
ctx.Response.Headers.Location = "/auth/captcha";
await ctx.Response.WriteAsync("Please click here to continue.");
Roblox.Metrics.ApplicationGuardMetrics.ReportBlockedUserAgent(ua);
return;
}
uaTimer.Stop();
if (!uaBlocked && !bypassOk && !bypassAllowedForPath)
Roblox.Metrics.ApplicationGuardMetrics.ReportAllowedUserAgent(ua);
var authTimer = new MiddlewareTimer(ctx, "a");
var isAuthorized = IsAuthorized(ctx);
authTimer.Stop();
if (isAuthorized || allowedUrls.Contains(normalizedPath) ||
RobloxPlayerDataRegex.IsMatch(normalizedPath))
{
appGuardTimer.Stop();
await _next(ctx);
return;
}
// If not blocked
if (FeatureFlags.IsDisabled(FeatureFlag.AllowAccessToAllRequests))
{
await Redirect(ctx, "/auth/home");
return;
}
// Otherwise, allow (almost) all
if (normalizedPath == "")
{
await Redirect(ctx, "/auth/home");
return;
}
appGuardTimer.Stop();
await _next(ctx);
}
}
public static class ApplicationGuardMiddlewareExtensions
{
public static IApplicationBuilder UseApplicationGuardMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ApplicationGuardMiddleware>();
}
}
using System;
class RobloxPlayerDataRegex
{
public static void Main()
{
// To resolve the error in the example, the first step is to
// move the declaration of conn out of the try block. The following
// declaration is available throughout the Main method.
RobloxPlayerDataRegex conn = null;
try
{
// Inside the try block, use the conn variable that you declared
// previously.
conn = new RobloxPlayerDataRegex();
}
catch (Exception e)
{
// The following expression no longer causes an error, because
// the declaration of conn is in scope.
if (conn != null)
Console.WriteLine("{0}", e);
}
}
}
but when i run dotnet run it gives this error:
E:\Datacenter\src\services\Roblox\Roblox.Website\Middleware\ApplicationGuardMiddleware.cs(405,1): error CS1529: A using clause must precede
all other elements defined in the namespace except external alias declarations [E:\Datacenter\src\services\Roblox\Roblox.Website\Roblo
x.Website.csproj]
Build failed. Fix build errors and rerun.
im very new at .NET, sorry if this question is stupid.
no DOTNET RUN Errors
var randnumber = CommonClass.Generate8DigitHBFNumber();
bool CheckCaseRef = CheckCaseRefIdAlreadyExistsInDB(randnumber);
if (CheckCaseRef)
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
else
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
//Method to Check the generated random number
bool CheckCaseRefIdAlreadyExistsInDB(string randnumber)
{
Log.Info("CheckCaseRefIdAlreadyExistsInDB started...");
bool checkCaseRef = false;
try
{
var ObjCustomerList = db.tblCustomers.ToList();
if (ObjCustomerList != null)
{
foreach (var customerlst in ObjCustomerList)
{
if (!(string.IsNullOrEmpty(randnumber)))
{
if (customerlst.CaseRef == randnumber)
{
checkCaseRef = true;
break;
}
}
}
}
else
{
return checkCaseRef;
}
}
catch (Exception ex)
{
Log.Error("Error CheckCaseRefIdAlreadyExistsInDB started...", ex);
return false;
}
return checkCaseRef;
}**
You might want to do this:
var randnumber = CommonClass.Generate8DigitHBFNumber();
while (! CheckCaseRefIdAlreadyExistsInDB(randnumber))
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
bool CheckCaseRefIdAlreadyExistsInDB(string randnumber)
{
return db.tblCustomers.Any(c => c.CaseRef == randnumber ?? "");
}
Checking the regenerated one would be an excellent use for recursion. If you don't know much about recursion, I would highly recommend doing some research on it first though, as it can lead to some really nasty memory issues in your code if used incorrectly.
//Code in main method
string randnumber = CheckRandomNumber();
//Recursive method to call
public string CheckRandomNumber()
{
string numToCheck = CommonClass.Generate8DigitHBFNumber();
if (db.tblCustomers.Any(x => x.CaseRef == numToCheck))
{
//Duplicate was found
CheckRandomNumber();
}
return numToCheck;
}
While using Dapper for multiple Query:
var result = sqlConnection.QueryMultiple(query, Parameters, commandType: commandType);
How can i get the table count returned from query? It has two overloaded implementation of .Read() method, which each time called, moves to next available result set (No result.Count() property). Eventually i want to put that number in a loop to iterate as many time as number of tables returned from query.
var reader = this.DbConnection.QueryMultipleAsync(sql, Params, commandType: CommandType.StoredProcedure).Result;
if(reader.IsConsumed == false)
{
DeviceTypeReport = reader?.ReadAsync<dynamic>().Result;
}
This is probably what you are looking for hope it helps.
This is probably what you are looking for hope it helps.
List<dynamic> data = new List<dynamic>();
while (reader.IsConsumed == false)
{
data.Add(await reader?.ReadAsync<dynamic>());
}
int totalRecordSet = data.Count;
public List NotificationExecuteMultiple(OutdoorRequest objreq, IConfiguration configuration)
{
var lst = new List<dynamic>();
using (DbConnection connection = new MySqlConnection(configuration.GetConnectionString("SquareHrConn")))
{
using (var dr = connection.QueryMultiple(ProcedureName, GetParamenter(objreq), commandType: CommandType.StoredProcedure))
{
while (dr.IsConsumed == false)
{
lst.Add(dr.Read());
}
}
}
return lst;
}
Consider the follwoing method to cover all cases
protected List<object> ExecuteMultiQuery<A, B, C, D, E, F, G, H, I, J>(string procedureName, DynamicParameters param = null)
{
List<object> result = new List<object>();
using (var connection = new SqlConnection(ConnectionManager.ConnectionString))
{
try
{
connection.Open();
using (var multi = connection.QueryMultiple(procedureName, param, commandType: CommandType.StoredProcedure, commandTimeout: 120))
{
var varA = multi.Read<A>();
if (varA != null) { result.Add(varA.ToList()); }
var varB = multi.Read<B>();
if (varB != null) { result.Add(varB.ToList()); }
var varC = multi.Read<C>();
if (varC != null) { result.Add(varC.ToList()); }
var varD = multi.Read<D>();
if (varD != null) { result.Add(varD.ToList()); }
var varE = multi.Read<E>();
if (varE != null) { result.Add(varE.ToList()); }
var varF = multi.Read<F>();
if (varF != null) { result.Add(varF.ToList()); }
var varG = multi.Read<G>();
if (varG != null) { result.Add(varG.ToList()); }
var varH = multi.Read<H>();
if (varH != null) { result.Add(varH.ToList()); }
var varI = multi.Read<I>();
if (varI != null) { result.Add(varI.ToList()); }
var varJ = multi.Read<J>();
if (varJ != null) { result.Add(varJ.ToList()); }
//if (varA != null) { result.Add(varA.ToList()); }
//if (resultSets > 1) { result.Add(multi.Read<B>().ToList()); }
//if (resultSets > 2) { result.Add(multi.Read<C>().ToList()); }
//if (resultSets > 3) { result.Add(multi.Read<D>().ToList()); }
//if (resultSets > 4) { result.Add(multi.Read<E>().ToList()); }
//if (resultSets > 5) { result.Add(multi.Read<F>().ToList()); }
//if (resultSets > 6) { result.Add(multi.Read<G>().ToList()); }
//if (resultSets > 7) { result.Add(multi.Read<H>().ToList()); }
//if (resultSets > 8) { result.Add(multi.Read<I>().ToList()); }
//if (resultSets > 9) { result.Add(multi.Read<J>().ToList()); }
return result;
}
}
catch (System.Exception e)
{
string message = e.Message;
}
}
return result;
}
I can't figure this out why I keep getting the compilation error: "not all code paths return a value". I am writing a simple class method that is supposed to return true if the account is available to use and false if the account is not available or is null/empty. The code for the method is below:
public static bool AccountAvailable(int AccountId)
{
try
{
bool accountavailable;
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
return accountavailable;
}
catch
{
}
}
Any help or advice on this would be appreciated. Thanks!!
If an exception is thrown in your code before you return a value then control moves to the catch block. It then reaches the end of the method without returning anything.
Either return something within, or after, the catch block.
In your catch block, add a return:
catch (Exception ex)
{
// your code
return null;
}
The suggest to try this code
public static bool AccountAvailable(int AccountId)
{
bool accountavailable = false;
try
{
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
}
catch
{
}
return accountavailable;
}
A weird situation has struck me this code was running successfully two days back, but i dont know why its not running as before now :
public static void ChangeStatus(int sessionID, int? participantID, Guid? temporaryParticipantID, int statustypeID)
{
using (EMSEntities entities = new EMSEntities())
using (TransactionScope ts = new TransactionScope())
{
try
{
SessionParticipant sessionParticipant = null;
CurrentSessionSeatsStatu sessionCurrentStatus = null;
if (participantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.ParticipantID == participantID)
.FirstOrDefault();
}
else if (temporaryParticipantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.TemporaryParticipantID == temporaryParticipantID)
.FirstOrDefault();
}
if (sessionParticipant != null)
{
sessionParticipant.StatusTypeID = statustypeID; // Status Changed here
}
**if (sessionParticipant.StatusTypeID == 2) // verified status
{
sessionCurrentStatus = entities.CurrentSessionSeatsStatus
.Where(a => a.SessionID == sessionID)
.FirstOrDefault();
if (sessionCurrentStatus.SeatsLeft > 0)
{
sessionCurrentStatus.SeatsLeft = sessionCurrentStatus.SeatsLeft - 1;
}
}**
entities.SaveChanges();
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
}
The problem is that changes(in StatusTypeID) for sessionParticipant are not saved in database but sessionCurrentStatus changes are !
no error thrown nothing !
Edit: I have discovered that the change in sessionparticipant is happening in all cases except when the status is changed to verified.
ie. when the other table viz. sessioncurrentstatus is updated in the if block.
That is whenever it goes in this if block(bold in code) the problem takes place.
Finally i found the problem and i think its because of the below code however it would be good if someone can explain the exact reason:
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // the position of this code line can be found in the below code
below is the code which called the ChangesStatus method:
protected void ddlStatuses_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < gridViewEvents.VisibleRowCount; i++)
{
if (gridViewEvents.Selection.IsRowSelected(i))
{
EMS.DAL.SessionParticipant sessionParticipant = (EMS.DAL.SessionParticipant)gridViewEvents.GetRow(i);
EMS.DAL.Session session = EMS.DAL.DALHelper.GetSessionById(sessionParticipant.SessionID);
EMS.DAL.DALHelper.ChangeStatus(sessionParticipant.SessionID, sessionParticipant.ParticipantID, sessionParticipant.TemporaryParticipantID, Convert.ToInt32(ddlStatuses.SelectedItem.Value));
if (ddlStatuses.SelectedItem.Value == "2" || ddlStatuses.SelectedItem.Value == "3") // if accepted or rejected
{
if (ddlStatuses.SelectedItem.Value == "2") // verified/accepted
{
EMS.DAL.DALHelper.SendMail("Congratulations! your participation for " + session.Name + " event has been confirmed.", "", sessionParticipant.Email, "");
// AT THIS POINT THE 'sessionParticipant' did not have the changed status which was set in the ChangeStatus method
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // culprit as per me
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail == null)
{
attendanceListDetail.AttendanceListID = a.ID;
attendanceListDetail.ParticipantID = sessionParticipant.ParticipantID.Value;
attendanceListDetail.IsPresent = false;
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Added);
}
});
}
else if (ddlStatuses.SelectedItem.Value == "3") // denied/rejected
{
EMS.DAL.DALHelper.SendMail("Your participation for " + session.Name + " event has been denied.", "", sessionParticipant.Email, "");
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified);
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Deleted);
}
});
}
}
else
{
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.DeleteAttendanceListDetail(attendanceListDetail);
}
});
attendanceList.ForEach(a =>
{
EMS.DAL.DALHelper.DeleteSessionAttendanceList(a);
});
}
}
}
gridViewEvents.DataBind();
RefreshSeats();
}