using sqlmapper.query in dapper with parameters - asp.net-mvc

I am creating a web app using web api mvc and I am using dapper.
Here is a scenario where I want to get the data in a list by validating user info
DynamicParameters param = new DynamicParameters();
param.Add("#fname", std.Fname);
param.Add("#lname", std.Lname);
param.Add("#action", "L");
IList<student> studlist = SqlMapper.Query<student>(con, "Stud_IUDV", param).ToList();
return studlist.ToList();
Here I want to get the data by validating these params and my storedprocedure looks like
if(#action='L')
//validation with select command
else
//select all data
and I am suppose to get
(validation with select command)
but else part of my storedprocedure is executing
What is wrong in my code?

IF(#action='L')
BEGIN
//validation with select command
END
ELSE
BEGIN
//select all data
END
This will solve your sql problem.

Related

How to get company's Active Directory data to display on a razor view(webgrid)?

I need to build a simple asp.net mvc web apps to display the detailed data from Active Directory and show it in a webgrid feature , is that possible? I appreciate if anybody can provide any good examples, thanks in advance.
I found this example: http://www.dotnetcodesg.com/Article/UploadFile/2/223/Get%20List%20of%20Active%20Directory%20Users%20in%20ASP.NET%20Csharp.aspx
but when I execute the codes, the program stopped on this line of code:
MembershipUser myUser = Membership.GetAllUsers()[searchResult...
I got error : "Unable to connect to SQL Server database. "
The codes stopped on :
MembershipUser myUser = Membership.GetAllUsers()[searchResult.Properties["sAMAccountName"][0].ToString()];
It seems I need to connect Membership database, do I have to connect membership database in order to get all employee data?
I only want to get all employee information such as : name, ID, email, phone , ,, and display them in a view (better in webgrid or other format easy to read).
I tried these codes :
DirectoryEntry myLdapConnection = new DirectoryEntry(LDAP://company.domin);
// DirectorySearcher search = new DirectorySearcher(myLdapConnection) { Filter = ("(objectClass=user)") };
DirectorySearcher search = new DirectorySearcher();
// search.CacheResults = true;
search.SearchRoot = myLdapConnection;
search.SearchScope = SearchScope.Subtree;
SearchResultCollection allResults = search.FindAll();
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("sAMAccountName");
.....
Basically, I added the data to a datatable and show them in a razor view, I got the data and displayed them on the razor view, but the data is not complete data, some employee information is missing, can anybody tell me what is wrong with my codes for the missing data? there must be something wrong with the codes which get the partial data. What I want to get is complete data in my company's Active Directory which includes all employee's name and group name, etc.
The database error message suggests that your site is configured for Forms Authentication. You need to set the authentication mode to Windows in your web.config file to use Active directory.
<system.web>
<authentication mode="Windows" />
</system.web>

SubmitChanges doesn't always update database

I am using ASP.NET MVC 4 (.NET framework 4.5) with LINQ-to-SQL and SQL Server 2008 R2
This function returns always true if I run it through debug mode, but when I run it without debug, it returns false. I once got this error: http://i.imgur.com/HydhT.png
I tried googling this, some similiar problems came up but I checked them all:
UserProfiles table has a primary key
The datacontext is in sync with the database
I've tried putting ConflictMode.ContinueOnConflict as an argument in SubmitChanges()
I've tried to put above the facebookID in LINQ designer: UpdateCheck=UpdateCheck.Never
Nothing works. I have never experienced anything like this before. Does anyone have any idea?
Code:
facebookID field in SQL Server is varchar(50) NULL with default value NULL
public static bool changeFacebookIDByEmail(string email, string facebookID)
{
UserProfile profile = (from s in _dc.Users
join u in _dc.Memberships on s.UserId equals u.UserId
join i in _dc.UserProfiles on u.UserId equals i.userID
where u.Email == email
select i).SingleOrDefault();
profile.facebookID = facebookID;
ChangeSet cs = _dc.GetChangeSet();
_dc.SubmitChanges();
if (cs.Updates.Count <= 0)
return false;
else
return true;
}
It seems like you are executing a manual SQL statement:
UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'
This will set the facebookID to null. Entity framework does not know this, though. It cannot interpret raw SQL. So it still thinks the facebookID is set to some value. When you later set it to that value in changeFacebookIDByEmail EF thinks nothing changed.
Sou you probably should not execute raw SQL strings. Use EF to change the value to null.
Change .singleordefault to .single I think your problem will be revealed pretty soon after that.
Basically anything found by your query with be in the datacontext. Anything new eg default will not.
You need to rewrite your routine to insert the new user in the case where it's not found.
EDIT
This is some code from a project I have been working on. I've cut out a bunch of stuff to demonstrate how it should work.
// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);
if (found == null)
{
found = new Identity
{
Domain = domain,
Password = User.Identity.AuthenticationType,
Salt = "",
UserName = userName,
LastUpdatedDateTime = DateTime.Now
};
dB.Identities.InsertOnSubmit(found);
}
dB.SubmitChanges(null);

How to check whether username already exists using ajax in asp.net?

I am working on an application which has a registration form and I have to display to the user whether the username exists or not.
I am using asp.net mvc3 and planned to use AJAX to achieve this.
I have a form
<tr>
<td>User Name*</td>
<td><input id="UserName" name="UserName" type="text" onblur="check(this.value);"/></td>
<td id= "UName"></td>
</tr>
which calls a .js file that has the folling contents
function check(User) {
...
var url = "/UserNameCheck/Index";
url += "?User=" + User;
xmlHttp.onreadystatechange = state_Change;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function state_Change() {
if (xmlhttp.readyState == 4) {// 4 = "Response loaded"
if (xmlhttp.status == 200) {// 200 = Response Error Free
document.getElementById("UName").innerHTML = xmlHttp.responseText
}
else {
alert("Problem retrieving XML data");
}
}
}
I alerted the username and I am getting the correct value that i had entered. Now, the URL is /UserNameCheck/Index where UserNameCheck is a controller and Index is a method in that.
The controller has this code.
public ActionResult Index(string User)
{
string UserName;
try
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
UserName = Request.QueryString["User"];
ConnectionPackage.ConnectionClass cc = new ConnectionPackage.ConnectionClass();
conn = cc.con;
string sql = "Select UserName FROM UserDetails where UserName = '" + UserName + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
object p = cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
string u = (string)p;
if (u.Length==0 || u.Equals("NULL") || u.Equals("null")||u.Equals("Null"))
{
return View();
}
return null;
}
catch (Exception ex){
}
and the view has
String buffer = " <table><tr><td id = 'UName' >" This user name already exists. Please select some other unser name.
buffer = buffer + "</td></tr></table>";
response.getWriter().println(buffer);
I also tried writing
Response.Clear();
Response.Write("UserName already exists. Please select another UserName");
Response.End();
instead of returning View.
But in both the cases, I didn't get any message that the username exists even though I typed a user name that was already present in the database.
The connection string work for inserting into the database, so I dont think there is a problem with that. Is there a problem with the URL that I have mentioned in the js file? Or is my entire approach wrong?
I am basically from java background so dont know much about asp.net. Please do help.
Thank you very much in advance.
I followed what was given in MSDN article How to: Implement Remote Validation in ASP.NET MVC
jQuery in Action is the most popular jQuery book
You're doing alright but you could make this a whole lot easier on yourself. If you are usinng MVC3 with Razor, your app already has jQuery installed.
Use the $.ajax() method to perform the calls to your controller action that checks names...
Bind the $.ajax() call "unobtrusively" which means instead of on your HTML control, bind the event to your control from the jquery/javascript.
Second, if you want a little fancy performance, you can bind it via the live() jquery function or keyup event, so that as you are typing the ajax call is made and you find out realtime.
Ultimately you will end up with a lot less javascript, and your JS stuff will be cleanly separated from your markup.
As far as your controller action is going, it looks fine for playing around and learning, but you'd want to think about either (a) putting your SQL statement as a stored procedure on the db server and calling that, or (b) writing a repository pattern class and then using LINQ to do your query work after the DB fetch.
Another possibility would be to use Entity Framework 4.1 via NuGet to eliminate both needs. It can have a bit of a learning curve, but there's lots of good stuff out there and your example would be fairly simple to get started with.
Let me know if you have any specific concerns with your code and I can provide a more detailed answer.

Query with ROWID via data provider

I am looking to query a table like the following sql:
select * from itd093 where rowid='Cumn99AAAAMzAAAAAJ'
It could find a unique record in the ADS architect client. However, when this query was sent from the code level through the .NET data provider, it return none result from the database server.
Does anyone have ideas on how I can make the sql above return the result through the .NET data provider?
Some sample code here:
public void DataProviderTest()
{
using (AdsConnection conn = new AdsConnection(#"Data Source=D:\Development\FDDB;ServerType=ADS_LOCAL_SERVER;TableType=ADS_CDX;TrimTrailingSpaces=TRUE;"))
{
conn.Open();
AdsCommand cmd = new AdsCommand("select * from itd093 where rowid='Cumn99AAAAMzAAAAAJ'", conn);
AdsDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (!reader.Read())
throw new Exception("no records");
}
}
Thanks Mark for pointing out that the .NET data provider and the Advantage Data Architect should return the same result.
The problem to be the different connection strings. From the help documentation, it says,the first six characters of the ROWID represent the database ID. It is based on the connection path.
I was mistakenly copy a rowid from the data architect to test with data provider, and the connection strings are different. That's why I couldn't get a result returned from the data provider as it does from the data architect.

symfony updates table but not form

My symfony edit form validates and saves. When I check the record in mysql query browser the record updates, but when the page refreshes the same data is there and the form hasn't updated. Any thoughts?
public function executeEdit(sfWebRequest $request)
{
$this->forward404Unless($items = Doctrine::getTable('items')->find(array($request->getParameter('item_id'))), sprintf('Object items does not exist (%s).', $request->getParameter('item_id')));
//make sure the item being edited is owned by the logged in user
$this->forward404Unless($items->getUser_id()==$this->getUser()->getGuardUser()->getId());
$cacheDir = sfConfig::get('sf_cache_dir').'/'. $app.'/'.$env.'/';
//Clear cache
$cache = new sfFileCache(array('cache_dir' => $cacheDir));
$cache->clean();
//set category id
$query=Doctrine_Query::create()
->select('name')
->from('categories')
->where('category_id="'.$items->category_id.'"')
->limit(1);
$category=$query->fetchArray();
#$items->category_id=$category[0]['name'];
$this->form = new itemsUserForm($items);
}
Two possibilities:
You have an open transaction in MySQL
You're not looking at the record in the browser you think you're looking at
I would make sure that #1 is not the case first. I believe you can do this by simply running the command
ROLLBACK;
If you have a transaction open, that will close it.

Resources