the process cannot access the file 'xxx.xml' because it is being used by another process - asp.net-mvc-4

I googled a lot, but i dint get any solution for problem.
Iam trying to add a node in to a xxx.xml file, but its throwing an error
"the process cannot access the file 'xxx.xml' because it is being used by another process", below is my class
public class Registration
{
List Users;
List NewUsers;
string Userpath = string.Empty;
string NewUserpath = string.Empty;
string strUsername = string.Empty;
public bool FINDUSERNAME(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
//Put code to get the offers from database to Offers variable
if (ReadXML(firstname, lastname, emailaddress, country, purchasedate, username, password))
return true;
else
return false;
}
//bool ReadXML(XmlDocument xmlfile2)
bool ReadXML(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
try
{
XmlDocument receivedxml = new XmlDocument();
Userpath = HttpContext.Current.Server.MapPath("/SampleData/Registration.xml");
NewUserpath = HttpContext.Current.Server.MapPath("/SampleData/NewRegistration.xml");
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = DtdProcessing.Ignore;
XmlReader xr = XmlReader.Create(Userpath, xrs);
if (xr != null)
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
}
Thanks in Advance...

It looks like you are never closing your reader, you need to call xr.Close() at some point. Or as Johan suggested, wrap it in a using statement:
using (XmlReader xr = XmlReader.Create(Userpath, xrs))
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
Also another note: I notice your method is named ReadXML, yet you are also writing XML in this method. This can be confusing, are you reading or writing? Part of your issue may also be that you are opening the file for reading, and then creating the file for writing?? I have not dealt with the C# Xml libs before but something doesn't seem right here. You might consider breaking this down more.

Related

How to get list of email address based on a specified group (CN) from memberOf Attribute in Active Directory in java

I had written a program to fetch all attributes from active directory based on username. now i want to get list of email address based on the group name CN= App_abc_Admin inside memerOf attribute.
Main .java
public void ldapQueryService()throws Exception{
try {
System.out.println("Querying Active Directory Using Java");
System.out.println("------------------------------------");
String domain = "abc.com";
String url = "ldap.abc.com:389";
String username = "username";
String password = "password";
String choice = "samaccountname";
String searchTerm = "xyz";
//Creating instance of ActiveDirectory
ActiveDirectory activeDirectory = new ActiveDirectory(username, password, domain, url);
//Searching
NamingEnumeration<SearchResult> result = activeDirectory.searchUser(searchTerm, choice, null);
while (result.hasMore()) {
SearchResult rs = (SearchResult) result.next();
Attributes attrs = rs.getAttributes();
String temp = attrs.get("samaccountname").toString();
System.out.println("Username : " + temp.substring(temp.indexOf(":") + 1));
String memberOf = attrs.get("memberOf").toString();
String stringToSearch = "CN=App_abc_Admin";
boolean test = memberOf.toLowerCase().contains(stringToSearch.toLowerCase());
if(test){
String mail = attrs.get("mail").toString();
System.out.println("Email ID : " + mail.substring(mail.indexOf(":") + 1));
}
}
activeDirectory.closeLdapConnection();
}catch(Exception e){
}
}
ActiveDirectory.java
public class ActiveDirectory {
//required private variables
private Properties properties;
private DirContext dirContext;
private SearchControls searchCtls;
private String[] returnAttributes = { "*"};
private String domainBase;
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)))";
public ActiveDirectory(String username, String password, String domainController,String url) {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "LDAP://" + url);
properties.put(Context.SECURITY_PRINCIPAL, username + "#" + domainController);
properties.put(Context.SECURITY_CREDENTIALS, password);
//initializing active directory LDAP connection
try {
dirContext = new InitialDirContext(properties);
} catch (NamingException e) {
//LOG.severe(e.getMessage());
//e.printStackTrace();
}
//default domain base for search
domainBase = getDomainBase(domainController);
//initializing search controls
searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(returnAttributes);
}
public NamingEnumeration<SearchResult> searchUser(String searchValue, String searchBy, String searchBase) throws NamingException {
String filter = getFilter(searchValue, searchBy);
String base = (null == searchBase) ? domainBase : getDomainBase(searchBase);
return this.dirContext.search(base, filter, this.searchCtls);
}
public void closeLdapConnection(){
try {
if(dirContext != null)
dirContext.close();
}
catch (NamingException e) {
//e.printStackTrace();
}
}
private String getFilter(String searchValue, String searchBy) {
String filter = this.baseFilter;
if(searchBy.equals("email")) {
filter += "(mail=" + searchValue + "))";
} else if(searchBy.equals("username")) {
filter += "(samaccountname=" + searchValue + "))";
}else if(searchBy.equals("title")) {
filter += "(title=" + searchValue + "))";
}else if(searchBy.equals("department")) {
filter += "(department=" + searchValue + "))";
}else if(searchBy.equals("givenname")) {
filter += "(givenname=" + searchValue + "))";
}
else if(searchBy.equals("samaccountname")) {
filter += "(samaccountname=" + searchValue + "))";
}
return filter;
}
private static String getDomainBase(String base) {
char[] namePair = base.toUpperCase().toCharArray();
String dn = "DC=";
for (int i = 0; i < namePair.length; i++) {
if (namePair[i] == '.') {
dn += ",DC=" + namePair[++i];
} else {
dn += namePair[i];
}
}
return dn;
}
}
In the above example i'm passing the search by and search term. But how to get list of users based on the CN in the memberOf attribute?
I tried to update the filter as below but no output
private String baseFilter = "(&(objectClass=Person)(memberOf=cn=App_abc_Admin,ou=Application Groups,dc=abc,dc=com))";
updated the filter as below.It works now
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)(mail=*abc.com)(memberOf=CN=App_abc_Admin,OU=Application Groups,OU=Security Groups,OU=Users_OU,DC=abc,DC=com))))";

How to insert current date and time when user insert data in database

I am trying to insert data into database. i am basically trying to get current date , I am also hiding that particular field("Update Date) because I do want the user to see. Now all I am wanting is whenever i insert some data to database created date should automatically inserted.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreImageCreateVM StoreImageVM)
{
if (ModelState.IsValid)
{
try
{
StoreImageLogic.Insert(StoreImageVM);
}
catch (Exception e)
{
TempData["Failure"] = "Creation Failed. Image too large.";
return View(StoreImageVM);
}
TempData["Success"] = "Creation Successful";
return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
}
return View(StoreImageVM);
}
savechangesmethod
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = imageVM.uploadDate;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
i just add to change the savechangesmethod by using the DateTime.Now method. see below.
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = DateTime.Now;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
}

Running SSIS from remote with WCF

I have a web service calling a ssis with no problem on localhost. But when i deploy it, it doesn't run and doesn't give any error. Where should i change to allow request from remote? I beleive that there is someting prevents requesting... This is my code.
public class blaService : IblaService
{
[WebMethod]
[WebGet(UriTemplate = "runSSISPackage/{Id}")]
public string runSSISPackage(string Id)
{
try
{
string pkgLocation = ConfigurationManager.AppSettings["dtsxPath"].ToString();
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
string databaseName, tableName, minId, maxId, sCreatedDateTime, filePathTemplate, folderName;
Int64 fileRowAmount, fileCount;
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString.SQL Server (SqlClient)"].ConnectionString.ToString()))
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("select * from dbo.Table where Id=" + Convert.ToInt32(Id), sqlConnection);
sqlCommand.CommandTimeout = 0;
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.Read())
{
databaseName = reader["DatabaseName"].ToString();
tableName = reader["TableName"].ToString();
minId = reader["MinimumId"].ToString();
maxId = reader["MaximumId"].ToString();
fileRowAmount = Int64.Parse(reader["FileRowAmount"].ToString());
fileCount = Int64.Parse(reader["FileCount"].ToString());
sCreatedDateTime = Convert.ToDateTime(reader["CreatedDateTime"]).ToString("yyyyMMddHHmmss");
filePathTemplate = ConfigurationManager.AppSettings["outputFilePath"].ToString();
folderName = "bla_" + sCreatedDateTime;
if (!Directory.Exists(string.Format(filePathTemplate + "\\{0}", folderName)))
{
Directory.CreateDirectory(string.Format(filePathTemplate + "\\{0}", folderName));
}
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["DBName"].Value = "bla_PasswordPool";
vars["FileCount"].Value = fileCount;
vars["FileName"].Value = "bla_" + sCreatedDateTime + "_1of1.txt";
vars["FileNamePrefix"].Value = "bla_" + sCreatedDateTime + "_";
vars["FileRowAmount"].Value = fileRowAmount;
vars["i"].Value = 0;
//vars["OutputFolder"].Value = #"C:\SSIS\blaSifreTakip\";
vars["OutputFolder"].Value = string.Format(filePathTemplate + "\\{0}", folderName);
vars["SelectSQLQuery"].Value = "select sifre from " + tableName + " where Id>" + minId + " And Id<=" + maxId + " order by Id";
vars["StartRowIndex"].Value = minId;
vars["TableName"].Value = tableName;
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
PasswordPackDataInfoEntity pp = new PasswordPackDataInfoEntity(Convert.ToInt32(Id));
pp.Status = 2;
pp.Save();
return "Success";
}
}
else
{
return "Empty";
}
}
return "";
}
catch (DtsException e)
{
return e.Message.ToString();
}
}
This is usually a permission issue between IIS and SQL Server (SSIS engine).
In IIS, look at the app pool that your WCF app (IIS folder) is using. If it is in the default pool, create a new pool and assign a utility account (to make things easier & isolated). That account needs permission to read files from your (configured) SSIS package folder and it needs admin permissions on the target database.
Here is a discussion thread that explains several pieces to the puzzle. It is a little wordy, but very thorough: http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/ff441dc3-b43b-486b-8be1-00126cf53812/

NameValueCollection in Windows Phone 8

I want to use NameValueCollection in windows phone 8, but I can not see this option in WP8 SDK. Can you help me please?
This function has been removed.
But a query can be manipulated using parsing and a SortedDictionary. i.e. This snippet sorts a query string:
public string sortQuery(string myUrl)
{
string url = myUrl.Substring(0, myUrl.IndexOf("?") + 1);
string q = myUrl.Substring(myUrl.IndexOf("?") + 1);
string[] pr = q.Split('&');
SortedDictionary<string,string> d = new SortedDictionary<string,string>();
foreach (string s in pr)
{
string[] prm = s.Split('=');
string key = prm[0];
string value = "";
if (prm.Length > 1) { value = "=" + prm[1]; }
d.Add(key, value);
}
string result = "";
foreach (var k in d.Keys)
{
result += k + d[k] + "&";
}
result = result.Substring(0, result.Length - 1);
return url + result;
}

Rewriting from MonoTouch Application to MonoDroid

I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.