Using multiple cookies in one web application - c#

I want to use cookies in my web application. My web application is a portal that accepts modules (some thing like dot net nuke). Now in my core I used cookies to store user language :
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Cookies["IPortalCookies"] == null)
{
using (var context = new EasyToUseEntities())
{
try
{
var lang = (from l in context.Core_Settings orderby l.SiteID descending select l).FirstOrDefault();
if (lang != null)
{
Response.Cookies["IPortalCookies"]["Language"] = lang.DefaultLanguage;
Response.Cookies["IPortalCookies"]["Direction"] = lang.DefaltDirection;
Response.Cookies["IPortalCookies"].Expires = DateTime.Now.AddYears(1);
}
else
{
Response.Cookies["IPortalCookies"]["Language"] = "en";
Response.Cookies["IPortalCookies"]["Direction"] = "ltr";
Response.Cookies["IPortalCookies"].Expires = DateTime.Now.AddYears(1);
}
}
catch (Exception)
{
Response.Cookies["IPortalCookies"]["Language"] = "en";
Response.Cookies["IPortalCookies"]["Direction"] = "ltr";
Response.Cookies["IPortalCookies"].Expires = DateTime.Now.AddYears(1);
}
}
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.Cookies["IPortalCookies"]["Language"]);
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(Request.Cookies["IPortalCookies"]["Language"]);
}
In one module I used cookies to store user visits, so the problem: When I install that module and cookie works, for first time it works fine, but when I am trying reload page or change page or any thing else it shows null reference error!
if (Request.Cookies["IPortalCookies"] != null)
{
if (Request.Cookies["IPortalCookies"]["Likes"] == null ||
Request.Cookies["IPortalCookies"]["Likes"].Contains("'" + articleid + "'") == false)
{
if (_ah.LikeIt(articleid))
{
Response.Cookies["IPortalCookies"]["Likes"] = Request.Cookies["IPortalCookies"]["Likes"] + ",'" + articleid + "'";
BindRepeater();
}
}
}

It Should be like this
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(Request.Cookies["IPortalCookies"].Values["Language"].ToString());
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(Request.Cookies["IPortalCookies"].Values["Language"].ToString())‌​;

Related

The provided anti-forgery token was meant for user "xxx", but the current user is ""

Hi I've looked through a lot of S.O. pages on this subject but mine is a little different. This has nothing to do with an anti-forgery protected login page or users hitting the back button. At our university we use University of Michigan's CoSign as a single-sign-on solution. Users are authenticated through cosign and on success the username is provided by the IIS server in Request.ServerVariables["REMOTE_USER"] and can then be used for authorization, etc.
Here's some code: in global.asax.cs:
Session["username"] = Request.ServerVariables["REMOTE_USER"];
On each page that might use Ajax (in a file Init.js; code from https://blog.alexmaccaw.com/jswebapps-csrf):
$(document).ready(function () {
SetCSRFHeader();
}
function SetCSRFHeader() {
var CSRF_HEADER = 'RequestVerificationToken';
var setCSRFToken = function (securityToken) {
jQuery.ajaxPrefilter(function (options, _, xhr) {
if (!xhr.crossDomain)
xhr.setRequestHeader(CSRF_HEADER, securityToken);
});
};
var theTokenVal = $('#__bothTokens').val();
setCSRFToken(theTokenVal);
}
In _Layout.cshtml:
#Html.AntiForgeryToken()
#{
string cookieToken, formToken, bothTokens;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
bothTokens = cookieToken + ":" + formToken;
}
<input type="hidden" id="__bothTokens" value="#(bothTokens)" />
I also wrote a class that implements IHttpModule to check all POST requests for the included header, parse it and validate it (code from https://security.stackexchange.com/questions/91164/how-to-check-the-origin-header-server-wide-in-iis-to-prevent-csrf):
public class HeaderCheck : IHttpModule
{
public HeaderCheck()
{
}
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
int errCode = 0;
int STATCODE = 403;
string cookieToken = "";
string formToken = "";
if (context.Request.HttpMethod == "POST") // only on POST requests
{
if (context.Request.Headers["Content-Type"] != null)
{
if (context.Request.Headers["Content-Type"] == "application/json;") // JSON check
{
if (context.Request.Headers["RequestVerificationToken"] != null)
{
string tokenHeaders = context.Request.Headers["RequestVerificationToken"];
string[] tokens = tokenHeaders.Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
else
{
errCode = 3;
}
}
else if (context.Request.Headers["Content-Type"].Length >= 19)
{
if (context.Request.Headers["Content-Type"].Substring(0, 19) == "multipart/form-data") // Form check
{
HttpCookie cookie = new HttpCookie("__RequestVerificationToken");
cookie = context.Request.Cookies["__RequestVerificationToken"];
formToken = context.Request.Form["__RequestVerificationToken"];
if (formToken == null) { tokenstr = "form null"; }
if (cookie != null)
{
cookieToken = cookie.Value;
System.Web.Helpers.AntiForgery.Validate(cookieToken, formToken);
}
else // cookie is null
{
errCode = 4;
}
}
}
else // neither acceptable content form
{
errCode = 5;
}
}
else // content type should not be null
{
errCode = 6;
}
if (errCode > 0)
{
try
{
System.Web.Helpers.AntiForgery.Validate(cookieToken, formToken);
}
catch (HttpAntiForgeryException e2)
{
string err = #"Antiforgery tokens not validated" +
"<br><b>Error in: </b>"
+ context.Request.Url.ToString()
+ "<br><b>Error Message: </b>"
+ e2.Message.ToString()
+ "<br><b>Stack Trace:</b><br>"
+ e2.StackTrace.ToString();
EmailContext.sendEmailOnError(err); // sends email to me for debugging
}
}
if (errCode > 0)
{
context.Response.StatusCode = STATCODE;
context.Response.Flush();
context.Response.End();
}
}
}
public void Dispose() { }
}
}
My questions: Why am I getting the error in the title of this question? How does AntiForgeryValidate know that the token was meant for me but somehow the token that's generated is for current user ""? Is there any way I can put the user into the token? I've even tried the advice at Reload AntiForgeryToken after a login to always regenerate the token the first time the user hits the home page (since they're already logged in at that point. Does this have anything to do with developing in visual studio in HTTP but the acceptance environment which is cosign-protected is https? Does it have anything to do with the fact that IIS is configured for Anonymous Authentication? (I think it needs to be to run under cosign).
Thanks for any advice.
EDIT: More and more I think this is due to IIS Anonymous Authentication being the only mode that's enabled. But any other mode requires some sort of second login, and since cosign is THE authentication provider, that doesn't help. So if anyone has any idea how to programmatically insert the user credentials received from cosign into IIS that might be the way forward.

How to update querystring without using response.redirect which affects on performace of application

Given code is working properly but while checking page url on redirect checker,it gives error as too many redirections which may affect on performace of app.
if (Request.QueryString[null] != null)
{
string LastIndexOFUrl = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
if (lang == "eng")
{
//Session["ServiceName"] = Request.QueryString[null].ToString();
//
dt2 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), LastIndexOFUrl);
if (dt2.Rows.Count > 0)
{
string Name_En = dt2.Rows[0]["URLEng"].ToString();
Name_En = Regex.Replace(Name_En, "[^0-9A-Za-z -]", "").ToLower().Replace(' ', '-');
if (Convert.ToString(Session["ServiceName"]) != Name_En)
{
Session["ServiceName"] = Name_En;
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Name_En);
}
else
Session["ServiceName"] = Name_En;
}
//
}
else
{
Session["ServiceName"] = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
//temp code:
dt1 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt1.Rows.Count > 0)
{
if (Session["ServiceName"].ToString() != dt1.Rows[0]["URLAr"].ToString())
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + dt1.Rows[0]["URLAr"].ToString());
}
Session["ServiceName"] = dt1.Rows[0]["URLAr"].ToString();
}
}
string sessionData1 = Session["ServiceName"].ToString();
}
else
{
if (Session["ServiceName"] == null)
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1342, 1343));
}
else
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Session["ServiceName"].ToString());
}
}
dt = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt.Rows.Count > 0)
{
ltContent.Text = dt.Rows[0]["longDesc"].ToString();
ltHeader.Text = dt.Rows[0]["name"].ToString();
hdnID.Value = dt.Rows[0]["ID"].ToString();
((DotNetNuke.Framework.CDefault)this.Page).Title = dt.Rows[0]["pageTitle"].ToString();
}
If you get "too many redirects" it's almost always because you have created an infinite loop of redirects by redirecting to the same page.
Step through the code in a debugger and carefully check the redirect urls.

Masterpage method returns null when firing a button event in a derived page

Basically on the master page I have a method which returns a "campaign" with the params of a unique Id and a user Id. Which works fine until I click a button in a derived page.
The problem is when I click a button in a derived page the method in the master page returns "null". Even when debugging I see the correct params.
EDIT// The Method that returns null:
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
Master page code:
protected void Page_Load(object sender, EventArgs e)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = User.GetLoggedInUser(securityToken);
if (user != null)
{
var convertedCampaignId = Request.QueryString["cid"];
//If the querystring exists process ELSE force
if (!string.IsNullOrWhiteSpace(convertedCampaignId))
{
using (var campaignRepository = new CampaignRepository())
{
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
//Does the campaign exist from the passed in query string,
if (campaign != null)
{
ccid = "'" + campaign.ConvertedCampaignId + "'";
//Build Navigation
StringBuilder sbNav = new StringBuilder();
string nav = KTO.Common.Reader.ReadFile("/templates/html/side-nav.html");
sbNav.AppendLine(nav.Replace("{convertedCampaignId}", campaign.ConvertedCampaignId));
ltlNavItems.Text = sbNav.ToString();
ltlCampaignName.Text = "Campaign: " + "<strong>" + campaign.Name + "</strong>";
//Get campaigns for dropdown
IEnumerable<Campaign> campaigns = campaignRepository.GetCampaigns(user.UserId);
StringBuilder sbCampaigns = new StringBuilder();
string strCampaigns =
"<li title='{campaignName}' data-cid='{convertedCampaignId}' class='js-campaign-item'>" +
"<p class='name-message'><a href='/panel/c/{convertedCampaignId}/' class='campaign-lnk'>{campaignName}</a>" +
"</p>" +
"</li>";
foreach (var c in campaigns)
{
sbCampaigns.AppendLine(strCampaigns.Replace("{convertedCampaignId}", c.ConvertedCampaignId)
.Replace("{campaignId}", c.CampaignId.ToString())
.Replace("{campaignName}", c.Name));
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
else
{
Response.Redirect("/login/");
}
}
Derived page logic:
protected void btnInviteUsers_Click(object sender, EventArgs e)
{
if (txtEmail.Text.Trim() != "")
{
if (txtEmail.Text.Trim().Length < 75)
{
if (Common.Email.IsValidEmail(txtEmail.Text.Trim()) == true)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = Business.Entity.User.GetLoggedInUser(securityToken);
if (user != null)
{
try
{
using (var userRepo = new UserRepository())
{
var userInSystem = userRepo.UserExists(txtEmail.Text.Trim().RemoveHtml());
if (userInSystem == true)
{
ltlReturnMessage.Text = "Unfortunately we cannot send the request, as the user already exists.";
}
else
{
//Craft querystring
string encryptedEmail = user.EncryptedEmail;
int uid = user.UserId;
string userInviteHTML = Common.Reader.ReadFile("/templates/emails/user-invite.html");
StringBuilder sb = new StringBuilder();
sb.AppendLine(userInviteHTML.Replace("{link}", "http://localhost:52447/_user-invite/?inor-t-em=" + encryptedEmail + "&inor-d=" + uid.ToString()));
Common.Email.SendMail(txtEmail.Text.Trim(), "", "", user.FirstName + " " + user.LastName + " invited you to join x", sb.ToString());
ltlReturnMessage.Text = "Invite sent!";
}
}
}
catch
{
ltlReturnMessage.Text = "Problem sending invite, please try again.";
}
}
}
else
{
ltlReturnMessage.Text = "Are sure that's an email address? Please try again.";
}
}
else
{
ltlReturnMessage.Text = "Email Address must not exceed 75 characters.";
}
}
else
{
ltlReturnMessage.Text = "Email Address required.";
}
}
Please consider the method does return a "campaign" on any page but just not when the page posts back.
After scrutinising every last line, I noticed that my query string was duplicated. When the button click event fired from my derived page it would post back thus running my logic on the master page. I would assume it played havoc with url-rewriting.
I fixed this by adding
frmInviteUser.Action = Request.RawUrl;
within the page_load of my derived page, which would force the request of the url and not postback to the master.
This is why I was getting a null on the method, the param passed was duplicated.
Regards,

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. when access local database

I have no idea.. why this occurs.
In debug mode it is running well .
however, now I am trying to run my project in IIS web server and
it doesn't runs well.
I can access the main page of my project. but when I try to access the local database, the following error shows up.
this is my log file and codes:
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine("아님여기?"+ex.Message);
file2.Close(); //디버깅 계속................
}
In this catch I have the following error:
provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
I am sorry that I can not explain which line is generating this exception because there's no exception occurring in debug mode...
Here is the code for Page Load:
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
WA = Request.QueryString["WA"];
if (string.IsNullOrEmpty(WA)) WA = "off";
string qstr = null;
qstr = Request.QueryString["vCnt"]; //ㅇㅈ이파라메터 들은 어디서...??
if (qstr != null && qstr != "") vCnt = Int32.Parse(qstr);
if (!IsPostBack)
{
Keywords = Request.QueryString["keywords"]; //ㅇㅈ search main -> searh 버튼 클릭
VideoSearch = Request.QueryString["VideoSearch"];//ㅇㅈ ~^~^~
// 스마트폰에서 포스팅 되었을 때
if (Request.UserAgent.Contains("Android"))
{
if (Request.Cookies["VIDEOSEARCH"] != null && Request.Cookies["VIDEOSEARCH"].Value != "")
{
VideoSearch = Request.Cookies["VIDEOSEARCH"].Value;
MAM.Models.Utils.CookieManager("VIDEOSEARCH", "");
}
}
if (!String.IsNullOrEmpty(Keywords) && !Keywords.Contains("null")) SearchTextbox2.Text = Keywords;
Debug.WriteLine("search text is " + SearchTextbox2.Text);
Debug.Flush();
try
{
if (!string.IsNullOrEmpty(VideoSearch))
{
//ㅇㅈ DNA를 추출하여 유사 동영상을 돌려받음.
string results = RetrieveDNAfromVideo(System.Web.HttpUtility.UrlDecode(VideoSearch)/*video name*/);
string[] lines = results.Split(new string[] { "\r\n" }, StringSplitOptions.None);
vSearchResults = new List<VSearchResult>();
foreach (string line in lines)
{
string[] words = line.Split(',');
VSearchResult vSearchResult = new VSearchResult();
vSearchResult.VideoID = Int32.Parse(words[0]);
vSearchResult.idx = Int32.Parse(words[1]);
vSearchResult.RGBdifferce = Int32.Parse(words[2]);
vSearchResults.Add(vSearchResult);
} //ㅇㅈ vSearchResults : RetrieveDNAfromVideo가 알려준유사동영상정보
MAMDataContext db = new MAMDataContext();
List<int> VideoIDs = (List<int>)vSearchResults.Select(v => v.VideoID).ToList();
//vdo = (List<Video>)(from a in db.Video
// join b in vSearchResults
// on a.id equals b.VideoID
// orderby b.RGBdifferce
// select a).ToList();
vdo = (List<Video>)(from a in db.Videos
where VideoIDs.Contains(a.id)
select a).ToList(); //ㅇㅈ vdo는 결국, RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들
vSearchResults2 = new List<VSearchResult2>();
VSearchResult v1 = null;
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v1 = vSearchResults.Where(t => t.VideoID == v.id).OrderBy(t => t.RGBdifferce).FirstOrDefault();//ㅇㅈ ㅇㄱㅁㅇ
// ㅇㅈ RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들[-> RGBdifferce가 가장작은 애] [] 무슨의미??
v2.idx = v1.idx;
v2.RGBdifferce = v1.RGBdifferce;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Serach done");
Debug.Flush();
}
if (!string.IsNullOrEmpty(Keywords))
{
string ret2 = null;
string str1 = null;
if (string.IsNullOrEmpty(Keywords))
{
Keywords = SearchTextbox2.Text;
}
if (string.IsNullOrEmpty(str1)) str1 = Keywords; //ㅇㅈ str1 은 질의의도??
string[] searchTextArray = str1.Split(' ');
int cnt1 = searchTextArray.Count();
string st1 = ""; string st2 = ""; string st3 = "";
if (cnt1 > 0) st1 = searchTextArray[0];
if (cnt1 > 1) st2 = searchTextArray[1];
if (cnt1 > 2) st3 = searchTextArray[2];
MAMDataContext db = new MAMDataContext();
vdo = (List<Video>)db.Videos.Where(v => v.overview.Contains(st1)
|| (cnt1 > 1 ? v.overview.Contains(st2) : false)
|| (cnt1 > 2 ? v.overview.Contains(st3) : false)).ToList();//ㅇㅈ 검색어를 overview에 가지고 있는 동영상 리스트
vSearchResults2 = new List<VSearchResult2>();
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v2.idx = 0;
v2.RGBdifferce = 0;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Search");
}
}
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine(ex.Message);
file2.Close(); //디버깅 계속................
}
Debug.WriteLine("Search End");
}
if (fUpload.PostedFile != null) //ㅇㅈ
{
fileupload1();
}
else
{
}
}
this is a guess because you did not provide a key information: the connection string.
my guess is that the application is using integrated authentication hence while debugging the access to the database is done using your credentials: as the developer you are likely allowed to do almost everything on the db so the application works correctly.
when the application is deployed the login to the database is performed using the credentials of the application pool used to run the application itself.
as a test you can change the user of the application pool on the iis server to use an account enabled on the db and retry to login.
there are two solutions:
- configure the application pool to use a specific windows user that is allowed to interact with the db
- change the connection string to log onto the db as a sql user (allowed to interact with the db)

checking virtual sub domains

I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it .
on local system it works finely .. but when I upload it on server it not works .. of course I change the commented place to uncomment for test .. but it's not working ..
it shows this error :
Object reference not set to an instance of an object.
My code is this in page load :
//Uri MyUrl = new Uri(Request.Url.ToString());
//string Url = MyUrl.Host.ToString();
Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = #fUsername", scn);
scm.Parameters.AddWithValue("#fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = #fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?
If it works fine locally, I guess the URL in the server has something to do with it.
Were you able to pinpoint exactly where you get the "Object reference not set to an instance of an object." exception? It would help to find the problem.
Anyway check this SO question where its mentioned that Request.Url.ToString() might behave differently in certain situations (Check the accepted answer) →
Request.Url.ToString() returns the machine name nested of the domain

Categories