Class in ASP.NET Partial Class in App_Code - c#

I created a class for connection and using with register.aspx without any problem. When i try to move codes from register.aspx.cs to regpartial.cs then i get an conflict error: "connection conn = new connection();"
I would like to move codes register.aspx.cs to mypartial.cs. I think it will be better but i'm not sure how can i solve conflict problem.
Register.aspx.cs (final)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using test.App_Code;
namespace test
{
public partial class register: System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
}
Connection.cs (final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace test.App_Code
{
public class connection
{
public SqlConnection connect()
{
SqlConnection conn= new SqlConnection("Data Source=******;Initial Catalog=****;Integrated Security=False;User Id=****;Password=*****;MultipleActiveResultSets=True");
baglanti.Open();
return (conn);
}
}
regpartial.cs (Final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test.App_Code.partials
{
connection conn = new connection();
public partial class regpartial : register
{
}
}

In general you shouldn't have much code inside your aspx.cs files.
You want to separate the logic that is directly your view/presentation logic (stuff that makes the .aspx pages work) from your business logic (sequencing, transformation, validation), and finally you want to have your Data Access / Resource Access to be isolated.
I'd also recommend using Dapper.NET over raw ADO.NET/SqlConnection.
I'm going to string together a very basic example of how you can separate this. This is not guaranteed to compile c# code but it will very close pseudocode.
Inside registration.aspx.cs
private void btnRegister_Click(object sender, EventArgs e)
{
var email = txtEmail.Text;
var password = txtPassword.Text;
var registration = new Registration { Email = email, Password = password }
var bizService = new RegistrationService();
var response = bizService.Register(registration);
if(response.Success) Response.Redirect("~/registration/success");
ltlError.Text = response.FailureMessage;
}
RegistrationService.cs
public class RegistrationService {
public RegistrationResponse Register(Registration req)
{
var regDAL = new RegistrationAccess();
var isEmailDuplicated = regDal.DoesEmailExist(req.Email)
if(isEmailDuplicated)
return new RegistrationResponse {
Success = false,
FailureMessage = "Email exists, did you mean to login instead?
}
regDAL.InsertNewRegistration(req)
return new RegistrationResponse { Success = true };
}
}
Lastly you should have a RegistrationAccess.cs that contains only code for reading and writing to SQL Server / other database / file system.
Note how the aspx.cs file has no knowledge of RegistrationAccess. Your view should not be directly calling the database. The other thing to note is that RegistrationService has no knowledge of the view. It receives a Registration type, then executes business logic and calls out to the DAL. The DAL class will have zero knowledge of both the view and the RegistrationService, it will know only one thing, the database.
This is the basis of a very simple ASP.NET webforms solution. A better solution would use the MVP/MVVM patterns and the Dependency Inversion Principle but those aren't worth using if you don't understand basic separation of concerns yet.

Related

Client web service for english dictionary

I use this service to translate English word:
http://services.aonaware.com/DictService/DictService.asmx?op=Define
I add this link to my windows Form application by click right on References -> Add Service Reference -> and best the URL of service in Address field.
then I write this 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 هجوم_الكسر_الأعمى.ServiceReference1;
namespace هجوم_الكسر_الأعمى
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Definition a = new Definition();
WordDefinition sv = new WordDefinition();
sv.Word="Go";
string b= sv.Word;
textBox1.Text = b; ;
}
}
}
The problem is that I don't have the result, I have the same world witch I write it "Go"?
You're not doing anything here, you're just creating an instance of WordDefinition locally that you set to the word you're trying to search for.
You need to invoke the service call, for example..
using (var dictionaryService = new ServiceReference1.DictServiceSoapClient("DictServiceSoap"))
{
var definition = dictionaryService.Define("Programming");
Console.WriteLine(definition.Definitions.First().WordDefinition);
}
I am not sure if I understand you, but if you would like to have result from sv.Word method I think you shloud try to check if there is some method with Result, for example: sv.WordResult and it will add event handler to this.

c# error: input string was not in a correct format

I'm a beginner in c#, currently attempting a windows form project. I've designed a form titled drugform. I use the dataset method to connect to the database. 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.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
using drugstoreform.BaseInfoTableAdapters;
namespace drugstoreform
{
public partial class DrugForm : Form
{
int Row = -1;
public DrugForm()
{
InitializeComponent();
}
private void Register_click(object sender, EventArgs e)
{
try
{
dbm_Medecine db = new dbm_Medecine();
db.Insert(Convert.ToInt32(DrugCode.Text.Trim()), DrugName.Text.Trim(), Convert.ToString(HowUse.Text.Trim()), Convert.ToDecimal(price.Text.Trim()));
}
catch(SqlException ex)
{
}
When I click on the register button, I get this error: input string was not in a correct format.
You get the error inConvert.ToInt32 and/or Convert.ToDecimal because the input was invalid. You can use int.TryParse and decimal.TryParse to validate it:
int drugCode;
decimal price;
if (int.TryParse(DrugCode.Text.Trim(), out drugCode) && decimal.TryParse(price.Text.Trim(), out price))
{
db.Insert(drugCode, DrugName.Text.Trim(), HowUse.Text.Trim(), price);
}
In the if drugCode and price are initialized with the correct value. Otherwise you should provide an error message that the user should provide correct input.
Possible reasons: perhaps the user enters 2.6 but the computer uses , as decimal separator. Or DrugCode.Text or price.Text are simply empty.

How to give Common path to video

I am working in project in which I have used vlc plugin v2. the path for my video is
axVLC.playlist.add(#"D:\My Project\Science\Resources\myvideo.mp4");
axVLC.playlist.play();
now the problem is when I build the project and give it to someone and he/she install it on his/her computer , it show exception that video path is wrong. I am sure that path is not suitable as my the video path in my project is D:... and he/she installed it on C.
So my question is that is there any way to give it common path by which user don`t face such kind of error
Import IO
Using System.IO;
then declare a string that will reference to your video folder
string AbsoluteRef;
use this code in your form load
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
Now declare a string for your video or which ever file like
string vlcvideo;
now add the two together
vlcvideo = AbsoluteRef & "myvideo.mp4";
Finnally add all this into your vlc plugin
axVLC.playlist.add(vlcvideo);
Complete Code looks like so.
using Microsoft.VisualBasic;
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.Windows.Input;
using yournamespace.Forms;
using System.IO;
namespace yourNameSpace
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string AbsoluteRef = null;
private void frmMain_Load(object sender, EventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
string vlcVideo = AbsoluteRef + "myvideo.mp4";
axVLC.playlist.add(vlcvideo);
}

Call a 'host' callback from a 'compiled assembly from source'

I'm compiling code on-the-fly using System.CodeDom.Compiler. Everything inside the compiled source works well, whatever I'm putting inside this source. I know how to call my functions:
o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
But let's say I'm using a WebClient to retrieve a string asynchronously using WebClient.DownloadStringAsync. Or any other context where I want my compiled source to tell to the host "Hey, I got a nice string ready for you." For the example, I've used a WebBrowser. Basically, I know how to deal with each of the two instances: My hosting program and the compiled program, but I want my compiled program to communicate with the host. By the way, I'm not a super-experimented programmer, so no obvious method comes to my mind.
What I've tried:
1 . I don't really need to try it because it would work, but I could use a timer reading a strings stack or tasks queue inside the compiled source, but the purpose of my application is to have +- 60 scripts able to execute ponctual tasks, not continuous background processes, so it wouldn't be efficient on the CPU.
2 . I've passed the handler to the compiled source like if it was in the hosting app:
//In the hosting app
MethodInfo mi2 = o.GetType().GetMethod("attachCallbackToHost");
mi2.Invoke(o2, new object[] { new WebBrowserNavigatedEventHandler (wb_navigated) });
//... And the handler
public static void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string browserHtmlFromCompiledSource = ((WebBrowser)sender).DocumentText;
MessageBox.Show(browserHtmlFromCompiledSource);
}
// Plain text from the compiled source code
public void attachCallbackToHost(WebBrowserNavigatedEventHandler handlerFromTheHost)
{
wb.Navigated += handlerFromTheHost;
}
And it did nothing.
3 . Maybe I could share a class or variable by passing it to the compiled assembly?
So, the question is either this or the other:
How to watch efficiently for change inside a specific variable or property inside the compiled program?
How to attach a callback to the host?
Ok. I got it: In order to access the host from the compiled source, the only thing required is to add the host assembly to the refered assemblies in the compiler parameters:
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
So no need for any special callback or INotifier.
Here's the full code that strictly answers my question and nothing more:
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 Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace MamaProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string source =
#"
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.Net;
using MyMama = MamaProgram;
namespace Baby
{
public class Program
{
public WebBrowser wb = new WebBrowser();
public void navigateTo(string url)
{
wb.Navigated += wb_navigated;
wb.Navigate(url);
}
public void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
MyMama.Form1.getResult(wb.DocumentText);
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
TreatWarningsAsErrors = false
};
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
compilerParams.ReferencedAssemblies.Add("System.Data.dll");
compilerParams.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add(typeof(System.ComponentModel.Component).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Compilation failed");
object o = results.CompiledAssembly.CreateInstance("Baby.Program");
MethodInfo mi2 = o.GetType().GetMethod("navigateTo");
mi2.Invoke(o, new object[] { "http://www.google.com" });
}
public static void getResult(string result)
{
MessageBox.Show(result);
}
}
}

using Microsoft Translate ( GetTranslation Service )

I'm going to build website that uses the translation service from Microsoft. I need to get all the available translations for each word but the code I have provides only one translation while it is supposed to give all available translations. Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using microsofttranslator;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel;
using TranslatorService;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{string Appid="my Appid";
string t="any text";
microsofttranslator.TranslateOptions options = new microsofttranslator.TranslateOptions();
options.Category = "general";
options.ContentType = "text/plain";
options.User = "TestUserId";
options.Uri = "";
bool a=true;
SoapService s = new SoapService();
microsofttranslator.GetTranslationsResponse translations = s.GetTranslations(Appid, t, "ar", "en", 5,a, options);
Response.Write(string.Format("Available translations for source text '{0}' are", t));
foreach (microsofttranslator.TranslationMatch translationMatch in translations.Translations)
{
Response.Write(string.Format("Translated text: {0}" + Environment.NewLine + " Rating:{1}" + Environment.NewLine + "Count:{2}" + Environment.NewLine, translationMatch.TranslatedText, translationMatch.Rating.ToString(), translationMatch.Count.ToString()));
} }}
I added Microsft translate WSDL as a web reference http://api.microsofttranslator.com/v2/Soap.svc?wsdl and I added TranslatorService as a service reference http://api.microsofttranslator.com/V2/Soap.svc
This code works well but as I said it gives only one translation while it is supposed to give all the available translations of a word. I cannot figure out what I am doing wrong.
Maybe you should use the "translateArray" method.
http://msdn.microsoft.com/en-us/library/ff512438.aspx

Categories