Creating ftp site programmatically - c#

i have written code to create new site in ftp. but its giving com exception. the code is attached for reference.
Exception details are
System.Runtime.InteropServices.COMException was unhandled
Message="Filename: \r\nError: Unrecognized element 'ftpServer'\r\n\r\n"
Source=""
ErrorCode=-2147023483
StackTrace:
at Microsoft.Web.Administration.Interop.IAppHostElement.GetElementByName(String bstrSubName)
at Microsoft.Web.Administration.ConfigurationElement.GetChildElement(String elementName)
at WindowsFormsTest.Form2.CreateFTPSite(String serverName, String siteName, String siteID) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 48
at WindowsFormsTest.Form2.button1_Click(Object sender, EventArgs e) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 25
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsTest.Program.Main() in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
code to create ftp site:
using(ServerManager serverManager = new ServerManager()) {
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement = sitesCollection.CreateElement("site");
siteElement["name"] = #"eMentorftp";
ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
bindingElement["protocol"] = #"ftp";
bindingElement["bindingInformation"] = #"*:21:";
bindingsCollection.Add(bindingElement);
ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");
ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
sslElement["serverCertHash"] = #"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
sslElement["controlChannelPolicy"] = #"SslRequire";
sslElement["dataChannelPolicy"] = #"SslRequire";
ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");
ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
basicAuthenticationElement["enabled"] = true;
ConfigurationElementCollection siteCollection = siteElement.GetCollection();
ConfigurationElement applicationElement = siteCollection.CreateElement("application");
applicationElement["path"] = #"/";
ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();
ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
virtualDirectoryElement["path"] = #"/";
virtualDirectoryElement["physicalPath"] = #"D:\Ftp";
applicationCollection.Add(virtualDirectoryElement);
siteCollection.Add(applicationElement);
sitesCollection.Add(siteElement);
serverManager.CommitChanges();

You can tell what your error is from the exception. Look at the first line in the exception stack trace:
System.Runtime.InteropServices.COMException
was unhandled Message="Filename:
\r\nError: Unrecognized element
'ftpServer'\r\n\r\n" Source=""
ErrorCode=-2147023483
First of all, we see "Unrecognized element 'ftpserver'" - which should tell us a lot about what happened when we look at your code. But in addition to that, we are provided an error code that tells us exactly why the COMException got thrown. If we decode the error code into an unsigned int (hex), we get:
0x80070585
This corresponds to an error code of:
8: Failure
7: Win32
585: (1413 decimal): Invalid Index (ERROR_INVALID_INDEX)
For more info on error codes, see HRESULT and Win32 error codes.
So, we threw a COMException becuase we used an invalid index. And we get an "unrecognized element 'ftpServer'" in the exception message. Looking at your code, you create a new ConfigurationElement siteElement by telling the sitesCollection to add a new element named "site":
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement = sitesCollection.CreateElement("site");
You then create a name for the site, and create bindings in the site's bindings collection:
siteElement["name"] = #"eMentorftp";
ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
bindingElement["protocol"] = #"ftp";
bindingElement["bindingInformation"] = #"*:21:";
bindingsCollection.Add(bindingElement);
Unfortunately, you then try to get a child element of the site using the name "ftpServer":
ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
But, the ConfigurationElement siteElement - which was just made - doesn't have a child named ftpServer! So we get an invalid index and throw an exception. Did you mean to create a child element in this line of code?
As an aside, I imagine that it's a COMException due to interop of the .NET interface to the underlying IIS7 COM objects. Not being an expert (at all) on the Microsoft.Web namespace, that's just a guess.

Related

C# .NET Missing Method Exception when opening ZipArchive created with System.IO.Compression

I have a C# WinForms .NET app in which I'm trying to write to a zip archive and read from it using System.IO.Compression.
Here's now I create the ziparchive:
public void SaveStdV20ZipProject(string strfilepath, clsProjectInfo GameInfo)
{
using (var ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
string strProjectData = String.Empty;
StringBuilder sb = new StringBuilder();
// First, we add the Game Info data...
sb.AppendLine(GameInfo.strGameVersion);
sb.AppendLine(GameInfo.strProjectType);
sb.AppendLine(GameInfo.strGameTitle);
sb.AppendLine(GameInfo.strAuthor);
sb.AppendLine(GameInfo.strCreationDate);
sb.AppendLine(GameInfo.blTSImagePresent.ToString());
sb.AppendLine(GameInfo.blTSAudioPresent.ToString());
sb.AppendLine(GameInfo.blTSVideoPresent.ToString());
sb.AppendLine(GameInfo.blFSSImagePresent.ToString());
sb.AppendLine(GameInfo.blFSSAudioPresent.ToString());
sb.AppendLine(GameInfo.blFSSVideoPresent.ToString());
sb.AppendLine(GameInfo.intTotalQuestions.ToString());
sb.AppendLine(GameInfo.intTotalMediaItems.ToString());
sb.AppendLine(GameInfo.intTotalCategories.ToString());
sb.AppendLine(GameInfo.blTiebreakerPresent.ToString());
// Next, create an archive entry for the Game Data string...
strProjectData = sb.ToString();
var ProjectData = archive.CreateEntry("ProjectData.txt");
using (var entryStream = ProjectData.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write(strProjectData);
}
// We're done writing all the data for this project. Now let's write it to the file...
using (var fileStream = new FileStream(#strfilepath, FileMode.Create))
{
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(fileStream);
}
}
}
}
And here's how I open it:
public void OpenStdV20ZipProject(string strfilepath)
{
string zipPath = strfilepath;
string extractPath = Path.GetTempFileName();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
using (StreamReader sr = new StreamReader(extractPath))
{
clsProjInfo.strGameVersion = (string)sr.ReadLine();
clsProjInfo.strProjectType = (string)sr.ReadLine();
clsProjInfo.strGameTitle = (string)sr.ReadLine();
clsProjInfo.strAuthor = (string)sr.ReadLine();
clsProjInfo.strCreationDate = (string)sr.ReadLine();
clsProjInfo.blTSImagePresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.blTSAudioPresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.blTSVideoPresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.blFSSImagePresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.blFSSAudioPresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.blFSSVideoPresent = Convert.ToBoolean(sr.ReadLine());
clsProjInfo.intTotalQuestions = Convert.ToInt32(sr.ReadLine());
clsProjInfo.intTotalMediaItems = Convert.ToInt32(sr.ReadLine());
clsProjInfo.intTotalCategories = Convert.ToInt32(sr.ReadLine());
clsProjInfo.blTiebreakerPresent = Convert.ToBoolean(sr.ReadLine());
}
}
}
}
} // <-THIS IS LINE 1320
It throws a Missing Method Exception and I've looked high and low in the Internet for a fix. Here's the stack trace:
System.MissingMethodException occurred
HResult=0x80131513
Message=Method not found: 'System.IO.Compression.ZipArchive System.IO.Compression.ZipFile.OpenRead(System.String)'.
Source=TASv20ClsLib
StackTrace:
at TASv20ClsLib.clsOpenStandardProject.OpenStdV20ZipProject(String strfilepath) in C:\Users\Reuben\Documents\Visual Studio 2017\Projects\C# Projects\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 Zip Test Jun14 2\TASv20ClsLib\Class1.cs:line 1320
at Trivia_Author_v20.frmMain.openV20ProjectToolStripMenuItem_Click(Object sender, EventArgs e) in C:\Users\Reuben\Documents\Visual Studio 2017\Projects\C# Projects\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 Zip Test Jun14 2\Trivia Author v10 New Approach\frmMain.cs:line 1627
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Trivia_Author_v20.Program.Main(String[] args) in C:\Users\Reuben\Documents\Visual Studio 2017\Projects\C# Projects\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 Zip Test Jun14 2\Trivia Author v10 New Approach\Program.cs:line 126
The ZipFile.OpenRead(string) method was added only in .NET 4.5. It does not exist in previous versions.
Your question is not clear about which version of .NET your project targets, nor which version of .NET is installed where you are trying to run it, but undoubtedly, you have targeted .NET 4.5 or higher, but are trying to run the code on which only an older version of .NET is installed.
To fix this, either make sure .NET 4.5 is installed on the machine where you want to run the code, or use the older API. For example, you can write your own OpenRead(string) method without much difficulty:
ZipArchive OpenRead(string filename)
{
return new ZipArchive(File.OpenRead(filename), ZipArchiveMode.Read);
}
}
This is part of a whole host of binding issues introduced in 4.6x versions of .Net Framework. It may work somewhere, but not other places.
Most of this is related binding redirect issues that they have had between 4.6.1 and 4.7.1. Fixed in 4.7.2. These issues usually manifest themselves when working in the Framework and referencing .Net Standard packages
It is addressed in this framework issue: https://github.com/dotnet/corefx/issues/7702
Your best bet is to use binding redirects in your .Config file, or upgrade to .Net Framework 4.7.2 or later
Here i used Ionic and its working good, You can use
You need to import Ionic.zip to your project.
using (var zip = Ionic.Zip.ZipFile.Read("YourFilePAth"))
{
<enter code here>
};

xaml parse exception issue only on win7

I have an issue where I got error
id 1000 (KERNELBASE.dll)
and
error id 1026 System.IO.FileNotFoundException
When I try to run my program on Win 7 (witch had run fine before), but it runs perfectly on win 8/8.1/10. I am running .Net Framework 4.5.
I had been trying to deleting the code, but then the error just appears on other lines off my code and thats keeps going on, so does anyone know how to fix it or know how to find out what actually are causing that issue
Binding Failure occurred
Message : Managed Debugging Assistant ' Binding Failure ' has detected a problem in ' F: \ Omini \ Omini Dækberegner.exe ' .
Additional information : the assembly with the display name ' PresentationFramework.Aero2 ' could not be loaded into the binding context '
C#
InitializeComponent();
bredebox_nu.Focus();
textBoxes = new List<TextBox> { bredebox_nu, profilbox_nu, Fælgestr_nu, bredebox_ny, profilbox_ny, Fælgestr_ny, oprofilbox, obredebox, oFælgestr };
win.SourceInitialized += new EventHandler(win_SourceInitialized);
List<biler> items = new List<biler>();
the other error
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087
Line Number = 616
Line Position = 48
Message = ' There were triggered an exception at setting the property ' System.Windows.FrameworkElement.Style ' . ' Line number ' 616 ' and line position ' 48' .
Source = Presentation Framework
Stack Trace :
by System.Windows.Markup.WpfXamlLoader.Load ( XamlReader xamlReader , IXamlObjectWriterFactory writer factory , Boolean skipJournaledProperties , Object rootObject , XamlObjectWriterSettings settings , Uri baseUri )
by System.Windows.Markup.WpfXamlLoader.LoadBaml ( XamlReader xamlReader , Boolean skipJournaledProperties , Object rootObject , XamlAccessLevel access level , Uri baseUri )
by System.Windows.Markup.XamlReader.LoadBaml ( Stream stream , ParserContext parserContext , Object parent , Boolean close stream)
by System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
by Omini_Tires_And_rims.MainWindow.InitializeComponent() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml:linje 1
by Omini_Tires_And_rims.MainWindow..ctor() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml.cs:linje 210
InnerException:
FileName=PresentationFramework.Aero2, PublicKeyToken=31bf3856ad364e35
FusionLog ==== state information prior binding ===
LOG: Display Name = PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35
(Partial)
WRN: There was delivered about a partial binding for assembly:
WRN: Assemblyname: PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35 | Domain ID: 1
WRN: A partial binding Occurs tabloid is only given part of assemblyens display name.
WRN This may cause the binder inputting a wrong assembly.
WRN: It is recommended to give up fully specified text ID for the Assembly,
WRN: consisting of the simple name, version, culture and token for the public key.
WRN: For more information and common solutions to this problem in the white paper http://go.microsoft.com/fwlink/?LinkId=109270.
LOG: Appbase = file: /// F: / Omini /
LOG: First PrivatePath = NULL
Calling assembly: Presentation Framework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35.
LOG: This binding initiates in loadingcontex default.
LOG: User application configuration file: F: \ Omini \ Omini Dækberegner.exe.Config
LOG: User host configuration file:
LOG: User machineconfigurationsfile from C: \ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ config \ machine.config.
LOG: Policy not applied to reference at this time (private, custom, partial, or location-based assemblybinding).
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.EXE.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.EXE.
)
HRESULT = -2147024894
Message = The file or the assembly ' PresentationFramework.Aero2 , PublicKeyToken = 31bf3856ad364e35 ' or one of its dependencies could not be loaded . The specified file was not found.
Source = mscorlib
StackTrace:
by System.Reflection.RuntimeAssembly._nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.InternalLoadAssemblyName (AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.Assembly.Load (AssemblyName assemblyRef)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveAssembly (BamlAssembly bamlAssembly)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlTypeToType (BamlType bamlType)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType (BamlType bamlType, int16 typeid)
by System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType (int16 typeid)
by System.Windows.Baml2006.Baml2006Reader.Process_ElementStart ()
by System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord ()
by System.Windows.Baml2006.Baml2006Reader.ReadObject (KeyRecord record)
by System.Windows.ResourceDictionary.CreateObject (KeyRecord key)
by System.Windows.ResourceDictionary.OnGettingValue (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.OnGettingValuePrivate (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValueWithoutLock (Object key, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValue (Object key, Boolean & canCache)
by System.Windows.DeferredResourceReference.GetValue (Base Value Source Internal value source)
by System.Windows.DependencyPropertyChangedEventArgs.get_NewValue ()
by System.Windows.Controls.Control.OnTemplateChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp)
by System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents)
by System.Windows.StyleHelper.DoStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle)
by System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache)
by System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
by System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
InnerException:
Xaml <GridViewColumn Header="Model" Width="140" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Model}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
i removed PresentationFramework.Aero2 from the references in visual studio and replaced it with PresentationFramework.Aero and deleted some of the themes and replaced the namespaces and now it runs fine on win 7 and win vista without any issues

subversion authentication with sharpsvn driver

I've set up my subversion server following the steps on : http://www.codinghorror.com/blog/2008/04/setting-up-subversion-on-windows.html
The server is running on my localhost
Configurations
this is my config file:
anon-access = read
auth-access = write
password-db = passwd
authz-db = authz
authz:
[/]
* = w
passwd:
[users]
plorio = pass
test = pass
Code using sharpSvn driver
var svn = new SvnClient();
svnClient.Authentication.DefaultCredentials = new NetworkCredential("test",
"pass",
new Uri("svn://localhost/main").AbsoluteUri);
var localFilename = "C:\\testFile.txt";
var commitArgs = new SvnCommitArgs();
commitArgs.LogMessage = "test";
svn.Commit(localFilename, commitArgs); // <<< error:
Error
svn.Commit(localFilename, commitArgs); gives the following error:
Commit failed (details follow):
innerException : {"Authentication error from server: Username not found"}
SvnErrorCode : SharpSvn.SvnErrorCode.SVN_ERR_RA_NOT_AUTHORIZED
SubversionErrorCode : 170001
StackTrace :
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, SvnException error) in f:\qqn\sharpsvn-dist-1.6\src\sharpsvn\svnclientargs.cpp:line 76
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, svn_error_t* error) in f:\qqn\sharpsvn-dist-1.6\src\sharpsvn\svnclientargs.cpp:line 42
at SharpSvn.SvnClient.Commit(ICollection`1 paths, SvnCommitArgs args, SvnCommitResult& result) in f:\qqn\sharpsvn-dist-1.6\src\sharpsvn\commands\commit.cpp:line 136
at SharpSvn.SvnClient.Commit(String path, SvnCommitArgs args) in f:\qqn\sharpsvn-dist-1.6\src\sharpsvn\commands\commit.cpp:line 74
at Zephyr.OnDemand.WorkbookManagementService.WorkbookManagementOperations.UpdateWorkbook(String client, ManagedWorkbookDetails details, Stream content) in C:\src\zod\ci-tests\SVN\WorkbookManagementService\WorkbookManagementOperations.cs:line 165
at SVN.Program.Main(String[] args) in C:\src\zod\ci-tests\SVN\Program.cs:line 24
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I am fairly confident the error exists in the subversion configuration or the svnClient.Authentication.DefaultCredentials if anyone has any ideas it would be helpful. Thanks in advance.
Problem
I was copying over my working directory from another Subversion working directory. This was problematic because I was also copied over the .svn folders. This caused the program to try and commit to the server defined in the .svn folder, which rendered the authentication error.
Solution
Delete .svn folders from working directory and re add and commit files

Entity Framework ExecuteStoreQuery fails on deployed systems

Ok, a bit stumped here, and instead of banging my head any more on this, I thought I'd toss this out to all the bright people here.
I'm using Entity Framework and c# for a WinApp solution, and the core of the problem is that the darned thing runs fine on my system, but after I deploy it, it fails. Even when I install the deployed app on my development system, it fails. I find that a bit disturbing.
To the nuts and bold of the issue. The user performs a search, I build a query, tap SQL via the ExecuteStoreQuery call and return a generic list of SearchResult objects.
The call:
retVal = ctx.ExecuteStoreQuery<SearchResults>(sql).ToList();
Alternate call also generates the same error:
ObjectQuery<DbDataRecord> c = ctx.CreateQuery<DbDataRecord>(sql);
The Error:
************** Exception Text **************
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly)
at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
at AMMCred.Data.Search.GetSearchResults(SearchTerms terms)
at AMMCred.frmMain.openProviderInfoToolStripMenuItem_Click(Object sender, EventArgs e)
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
SearchResults is a custom object, like so:
public class SearchResults : IEquatable<SearchResults>
{
private Guid id = Guid.Empty;
public Guid PROV_MPI_NO
{
get { return id; }
set { id = value; }
}
private string iPA = "";
public string IPA
{
get { return iPA; }
set { iPA = value; }
}
private string firstName = "";
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string middleName = "";
public string MI
{
get { return middleName; }
set { middleName = value; }
}
private string lastName = "";
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string license = "";
public string License
{
get { return license; }
set { license = value; }
}
private string provId = "";
public string ProvId
{
get { return provId; }
set { provId = value; }
}
/// <summary>
/// Used to help identify duplicates in a collection
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(SearchResults other)
{
return (this.PROV_MPI_NO == other.PROV_MPI_NO && this.License == other.License);
}
}
And finally, here is the select part of the SQL being used to obtain the search results:
SELECT a.PROV_MPI_NO, b.COMPANY_ID AS IPA, a.FIRSTNAME,a.MI,a.LASTNAME, b.PROVID, c.LICENSE
The problem seems to be coming from within Entity Framework as it's binding the results of the SQL to the custom object. I've verified that the custom object field names are the same as the SQL fields in case that mattered, which it didn't seem to.
It's darn near time for me to leave, and I'll be pondering this all weekend, so I'll probably check back in from time to time to answer any questions anyone might have.
Like I said, I'm completely stumped at the moment and would totally appreciate anyone's insight.
Thanks in advance!
Wayne
UPDATE 11/14/2011----------
Ran the Assembly Binding Log Viewer tool and came up with the following lead. Looks like Microsoft.Practices.Unity isn't loading. Thing is, I never once referenced these Practices assemblies in ANY application, but it seems that System.Data.Entity does...go figure. It's a lead...any info on this new development is so very appreciated.
*** Assembly Binder Log Entry (11/14/2011 # 3:10:52 PM) ***
The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable C:\Users\***me***\AppData\Local\Apps\2.0\1ND1AZ7G.HEJ\CWDQKK8A.LVO\ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4\AMMCred2.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = ***me***
LOG: DisplayName = Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
(Fully-specified)
LOG: Appbase = file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = AMMCred2.exe
Calling assembly : Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\***me***\AppData\Local\Apps\2.0\1ND1AZ7G.HEJ\CWDQKK8A.LVO\ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4\AMMCred2.exe.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity.DLL.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity/Microsoft.Practices.Unity.DLL.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity.EXE.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity/Microsoft.Practices.Unity.EXE.
LOG: All probing URLs attempted and failed.
The error is a load exception.
Since this works in development, but not in the deployed program, it is probably due to the dll not being included.
Go into your VS project, expand the references and check the properties of each dll, make sure that copy local = true for the dll's that are not being deployed.
Based on your bind result, it looks like you are not deploying Microsoft.Practices.Unity.DLL with your application. And it looks like this is referenced from Microsoft.Practices.EnterpriseLibrary.Common, which is why you don't have a direct reference.
Here is the MSDN article that describes the various dependencies that the Enterprise Library has.
Update
I just checked the direct dependencies of System.Data.Entity using ildasm.exe (C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin) and it definitely does not reference the enterprise library. I would have been extremely surprised if it had, because they generally don't create dependencies between System DLLs and optional product DLLs (just for this reason).
Are you pulling in other DLLs/references that may include this? If you aren't sure, you can use ildasm.exe, navigate to the DLL, then open it's manifest. It's a little hard to read, but you are looking for references like:
module extern 'System.Data.dll, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
and
.assembly extern System.Data

Unhandeled exception in application

I have been working on a code that will grab the userName from the local machine and place it in a log file and start a .exe if the username has not been recoreded into the log file. I was able to run the code on my local machine, but when I put it on the server and run it I am given an error that reads:
"Unhandeled exception has occurred in your applications"
Details:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
***** Exception Text *******
System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(String fileName)
at User.Form1.Form1_Load(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
And here is my code////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace User
{
public partial class Form1 : Form
{
public const string dir = #"C:\Numara";
public const string path = dir + #"\Audit.log";
public const string TrackIT = #"\\tkahd-nti-1\TrackIt\Audit32.exe /Q";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//returns user name
//label1.Text = System.Environment.UserName.ToString();
string userName = System.Environment.UserName; //user name
if (!Directory.Exists(dir))
//directory does not exist
//create it
Directory.CreateDirectory(dir); //creates directory
//by this point directory is created
//now check file
if (!File.Exists(path))
//file does not exist, so create it
File.Create(path);
//Read data from the .dat file
string line = System.IO.File.ReadAllText(path);
//if the name of the logged in user
//is the same as the user name of the text file
//then exit program
if (line == userName)
Application.Exit();
else
//clear fields and write new name to file and begin audit
{
//clears fields
using (FileStream stream = new FileStream(#"C:\Numara\Audit.log", FileMode.Create))
{
using (TextWriter writer = new StreamWriter(stream))
{
//writer.Write("");
writer.Write(userName);
}
// writes new name to file
}
//StreamReader textIn =
// new StreamReader(
// new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
//begins audit
Process.Start(TrackIT);
Application.Exit();
}
}
}
}
The exception is being thrown because the process can't find the following network path:
\\tkahd-nti-1\TrackIt\Audit32.exe
The most likely cause is that the user account that the application is running under doesn't have access to that directory.
From your comments below it seems that the app is running using the permissions of the user who is logging on. You would need to grant anyone who might login read-only access to the "Audit32.exe" application.
However you don't need your own application to do this. If you open "Local Security Policy" from "administrative tools" (usually in control panel) you can open up the Local Policies --> User Rights Assignment folder from the tree view on the left and then change the "Log on locally" and "deny logon locally" settings to allow/deny login to individual users or groups of user. but be careful not to lock yourself out of the machine.
Try fully trusting the share...
http://blogs.msdn.com/b/shawnfa/archive/2004/12/30/344554.aspx?wa=wsignin1.0

Categories

Resources