checking virtual sub domains - c#

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

Related

C# Value cannot be null. Parameter name: user

In my C# application I use 2 connection strings (application_cs, users_cs). To change these connection strings I use:
private static void SetProviderConnectionString(string connectionString)
{
var connectionStringFieldM =
Membership.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldR = Roles.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldP = ProfileManager.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringFieldM.SetValue(Membership.Provider, connectionString);
connectionStringFieldR.SetValue(Roles.Provider, connectionString);
connectionStringFieldP.SetValue(ProfileManager.Provider, connectionString);
}
public static void SetProviderUsers()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["users_cs"].ConnectionString);
}
public static void SetProviderApp()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["application_cs"].ConnectionString);
}
So in my code whenever I want to add a user I do this:
public int CreateUser(int stid, int cid, int usrId, string email, string tel, string mob, string username,
bool create, bool prime)
{
int result = 0;
Guid userid = new Guid();
DALUsers.UserDBDataContext dc = new DALUsers.UserDBDataContext();
DAL.AppDataContext d = new DAL.AppDataContext();
BLL.Security.SetProviderUsers();
if (create) //create the user first
{
string question = "1";
string answer = "1";
bool isAproved = true;
string password = System.Web.Security.Membership.GeneratePassword(8, 2);
MembershipCreateStatus cs = new MembershipCreateStatus();
MembershipUser newUser = Membership.CreateUser(username, password, email, question, answer, isAproved, out cs);
Membership.UpdateUser(newUser);
Roles.AddUserToRole(username, "User_x");
if (cs == MembershipCreateStatus.Success)
{
result = 1;
}
else
X.MessageBox.Info("Error", "Cannot create user due to :" + cs.ToString(), UI.Danger).Show();
}
//at this point we have the user created either way.
// return userid;
var id = (from i in dc.aspnet_Users where i.UserName.CompareTo(username) == 0 select i.UserId);
if (id.Count() == 1)
{
userid = id.First();
bool contin = true;
var fulname = (from i in dc.Clients where i.id == usrId select i).First();
if (String.IsNullOrEmpty(fulname.Mobile)) fulname.Mobile = mob;
fulname.Email = email;
fulname.ModifiedBy = HttpContext.Current.User.Identity.Name;
fulname.ModifiedDate = DateTime.Now;
dc.SubmitChanges();
DateTime dt = DateTime.Now;
DALUsers.CIUser usr = new DALUsers.CIUser();
var existing = (from i in dc.CIUsers where i.UserName.CompareTo(username) == 0 && i.cid == cid select i);
if (existing.Count() > 0)
{
X.MessageBox.Info("Warning", "UserName already exists . Please try another!", UI.Warning).Show();
contin = false;
}
else
{
dc.CIUsers.InsertOnSubmit(usr);
dc.SubmitChanges();
}
if (contin)
{
DALUsers.CIUser usrNew = new DALUsers.CIUser();
var approved = (from k in dc.aspnet_Memberships //if user is not approved
where k.UserId == userid
select k).FirstOrDefault();
if (approved.IsApproved == false)
{
approved.IsApproved = true;
}
ProfileBase profile = ProfileBase.Create(username);
profile.SetPropertyValue("Mobile", mob);
profile.SetPropertyValue("Email", email);
profile.Save();
usrNew.UserId = usrId;
usrNew.cid = cid;
usrNew.FullName = fulname.LastName + " " + fulname.FirstName;
usrNew.Role = "User_x";
usrNew.SignRights = prime;
usrNew.IsPrime = prime;
usrNew.stid = stid;
usrNew.UserName = username;
usrNew.UserId = userid;
usrNew.CreatedDate = DateTime.Now;
usrNew.CreatedBy = HttpContext.Current.User.Identity.Name;
dc.CIUsers.InsertOnSubmit(usrNew);
dc.SubmitChanges();
result = 1;
X.MessageBox.Info("Success", "The user has been successfully added", UI.Success).Show();
}
}
else
X.MessageBox.Info("Error", "Could not find the user", UI.Danger).Show();
BLL.Security.SetProviderApp();
return result;
}
EDIT
I just saw that in my code there is this line:
DALUsers.aspnet_User user = new DALUsers.aspnet_User();
But the variable user is not used anywhere else in the code. Probably it has been left there... And its the only variable named user in my code. Is that causing the issue? But then why only on the production server?
EDIT
The weird part is that when I run my application from visual studio locally it works as a charm. But when I am adding a user in the application running on the production server when I am trying to add the second user it fails and I receive this error:
Value cannot be null. Parameter name: user
And if I try to login to my application after that it fails. I have to restart my website from iis to be able to login again.
Any ideas?
Well I cant find the error in your code but if you say that this error occurs only in server and that you are sure that your files are synched between server and your local machine, then probably the error lies in your web.config. Take a look

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.

Using multiple cookies in one web application

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())‌​;

How to retrieve connectionStrings from Server Explorer

I would like to write an extension to Visual Studio, which will enable me to generate a model for specified table.
I have used the following code to add MyCommand item into context menu of table in server explorer:
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar menuBarCommandBar = ((CommandBars)_applicationObject.CommandBars)["Object Node"];
Command command = commands.AddNamedCommand2(_addInInstance, "MyCommand", "MyCommand",
"Executes the command for MyCommand", true, 59, ref contextGUIDS,
(int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
if ((command != null) && (menuBarCommandBar != null))
{
command.AddControl(menuBarCommandBar, 1);
}
To get the name of the selected Table item:
string fileName = "Dafault.cs";
var serverExplorer = _applicationObject.ToolWindows.GetToolWindow("Server Explorer") as UIHierarchy;
if (serverExplorer != null)
{
dynamic item = ((object[])serverExplorer.SelectedItems)[0];
fileName = string.Format("{0}.cs", item.Name);
}
//...
// Generate model based on table from database
//...
_applicationObject.ItemOperations.NewFile("General\\Text File", fileName, Constants.vsViewKindCode);
How can I get information about the database connection?
Brad Larson, why my question was deleted?
Found the solution.
Used this
public static IDbConnection GetConnection(DSRefNavigator navigator, out string type)
{
type = null;
try
{
if (navigator != null)
{
IVsDataConnectionsService dataConnectionsService =
(IVsDataConnectionsService) Package.GetGlobalService(typeof(IVsDataConnectionsService));
string itemName = navigator.GetConnectionName();
if (itemName != null)
{
int iConn; // = dataConnectionsService.GetConnectionIndex(itemName);
DataViewHierarchyAccessor dataViewHierarchy = null;
for(iConn = 0; iConn < dataConnectionsService.Count; iConn++)
{
DataViewHierarchyAccessor hierarchyAccessor =
new DataViewHierarchyAccessor((IVsUIHierarchy) dataConnectionsService.GetConnectionHierarchy(iConn));
try
{
if (hierarchyAccessor.Connection.DisplayConnectionString == itemName)
{
dataViewHierarchy = hierarchyAccessor;
break;
}
}
catch
{
}
}
if (dataViewHierarchy != null)
{
DataConnection connection = dataViewHierarchy.Connection;
if (connection != null && connection.ConnectionSupport.ProviderObject != null)
{
type = connection.ConnectionSupport.ProviderObject.GetType().FullName;
return (IDbConnection) connection.ConnectionSupport.ProviderObject;
}
}
}
}
}
catch
{
}
return null;
}

Authenticating a web service for transferring a file?

I have a web service that transfers a file, and i want to authenticate that the source of the transfer has access. I authenticate all my clients by their user SID that gets pulled from AD, which is then encrypted and stored in a DB. The problem i am running into is that the client transferring the file calls the service every 49152 bytes. So basically I dont want it to make a DB call every time a new byte array comes in. Any idea how i could just make it call the DB once to verify the encrypted SID is authenticated once and then trust it until complete?
Here is my code:
public class TransferFile : System.Web.Services.WebService
{
int Authenticated = 0;
[WebMethod]
public void WriteBinaryFile(string userSID, byte[] buffer, string FileName)
{
string ConnectionString = null;
string DBServer = null;
string AuthenticationMethod = null;
string DB_U = null;
string DB_P = null;
string DBName = null;
try
{
XmlReader xmlReader = XmlReader.Create(#"C:\Program Files\SM\SM_DB_Config.xml");
while (xmlReader.Read())
{
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_Server"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DBServer = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_Name"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DBName = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_AuthenticationMethod"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
AuthenticationMethod = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_U"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DB_U = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_P"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DB_P = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
}
xmlReader.Close();
if (AuthenticationMethod == "Integrated")
{
ConnectionString = "Data Source=" + DBServer + ";Provider=SQLOLEDB;Initial Catalog=" + DBName + ";Integrated Security=SSPI;";
}
else
{
ConnectionString = "Data Source=" + DBServer + ";Provider=SQLOLEDB;Initial Catalog=" + DBName + ";User ID=" + DB_U + ";Password=" + DB_P;
}
String query = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = ?";
OleDbConnection conn = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("userSID", userSID.ToString());
conn.Open();
int returnCount = (Int32)cmd.ExecuteScalar();
conn.Close();
if (returnCount >= 1)
{
Authenticated = 1;
}
else
{
Authenticated = 0;
}
}
catch (Exception ex)
{
}
if (Authenticated == 1)
{
string PathName = #"C:\Test\";
using (FileStream fs = new FileStream(PathName + FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.End);
fs.Write(buffer, 0, buffer.Length);
}
}
}
}
If your only concern is hitting the db frequently, I would suggest you cache the SID in your webservice as authenticated. Whenever you get a request, check if the value exists in the cache and if it is not there, then hit the db. Also you should set a optimal time for expiration.
You could use HttpRuntime.Cache for this purpose.
Code to set the value in Cache
HttpRuntime.Cache.Insert(userSID, 1, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0))
Code to get the value from Cache
HttpRuntime.Cache.Get(userSID)
Maybe you can save the first result in the ASP.NET Cache. See http://msdn.microsoft.com/en-us/library/aa480499.aspx
You can save objects (like the validation variable) in cache like this:
var Authenticated = ... (the value that you already have)
HttpContext.Current.Cache.Insert(
"myAuthenticatedCacheKey",
Authenticated,
null, DateTime.Now.AddMinutes(10), // 10 minutes expiration
System.Web.Caching.Cache.NoSlidingExpiration
);
And you can recover them like this:
var Authenticated = HttpContext.Current.Cache.Get("myAuthenticatedCacheKey");
Another way to go could be using the Application object (The same as the Session object but with an application scope and it is shared between all the sessions). You can store and retrieve objects from the Application scope like the following:
Session("myAuthenticatedSessionKey") = Authenticated;
...
var Authenticated = Session("myAuthenticatedSessionKey");
Please notice that you need to cast the objects when retrieving them from Cache or Application objects.

Categories