4 Mayıs 2015 Pazartesi

Mock ModelState

This may be a silly example, but hopefully it moves the discussion forward:
The following code is in my Controller Action: 
if (ViewData.ModelState.Count > 10)
{
ViewData["Message"] = "Too many errors to continue";return View();
}
Here is a test with mocking and a test wtihout mocking:
[Test]public void Test11ModelStateErrorsWithMock()
{
HomeController homeController = new HomeController();

MockRepository mockRepository = new MockRepository();
ModelStateDictionary mockModelStateDictionary = (ModelStateDictionary)mockRepository.DynamicMock(typeof(ModelStateDictionary));
homeController.ViewData.ModelState = mockModelStateDictionary;
Expect.Call(mockModelStateDictionary.Count).Return(11);
mockRepository.ReplayAll();
ViewResult viewResult = (ViewResult)homeController.About();
mockRepository.VerifyAll();
Assert.AreEqual("Too many errors to continue", viewResult.ViewData["Message"]);
}
[Test]public void Test11ModelStateErrorsWithoutMock()
{
HomeController homeController = new HomeController();
homeController.ViewData.ModelState.AddModelError("1""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("2""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("3""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("4""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("5""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("6""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("7""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("8""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("9""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("10""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("11""FakeValue""FakeException");
ViewResult viewResult = (ViewResult)homeController.About();
Assert.AreEqual("Too many errors to continue", viewResult.ViewData["Message"]);
}

In my opinion, the test with the mock is less verbose and shows the intent better.  It is easier to change (for example if the requirement changed to having a limit of 20 errors).

2 Mayıs 2015 Cumartesi

Hatalar

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

An error occurred while updating the entries. See the inner exception for details

inner exception i incele ordan bulursun

LINQ ile rastgele şifre üretmek

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
    Enumerable.Repeat(chars, 8)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());

ASP.NET Request.Url Özellikleri

Some HttpRequest path and URL properties:
Request.ApplicationPath: /uyeler
Request.CurrentExecutionFilePath: /uyeler/istanbul/Test.aspx
Request.FilePath: /uyeler/istanbul/Test.aspx
Request.Path: /uyeler/istanbul/Test.aspx
Request.PathInfo:
Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\uyeler\
Request.RawUrl: /uyeler/istanbul/Test.aspx?query=arg
Request.Url.AbsolutePath: /uyeler/istanbul/Test.aspx
Request.Url.AbsoluteUri: http://localhost:96/uyeler/istanbul/Test.aspx?query=arg
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.Authority: localhost:1395
Request.Url.LocalPath: /uyeler/istanbul/Test.aspx
Request.Url.PathAndQuery: /uyeler/istanbul/Test.aspx?query=arg
Request.Url.Port: 1395
Request.Url.Query: ?query=arg
Request.Url.Scheme: http
Request.Url.Segments: /
uyeler/
istanbul/
Test.aspx

Metnin içindeki değerleri listeden replace etme

                string htmlFile =
                    File.ReadAllText(
                        HttpContext.Current.Server.MapPath("~/Views/Shared/Mail/_RememberPassword.html"));
                var htmlData = new Dictionary<string, string>();
                htmlData.Add("{resetLinkId}", "link");
                htmlFile = htmlData.Aggregate(htmlFile, (current, item) => current.Replace(item.Key, item.Value));

1 Mayıs 2015 Cuma

Remember password

        public Result RememberPassword(string username)
        {
            try
            {
                var user = Context.Users.Find(username);
                var smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/no_reply");
                var smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port)
                {
                    Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password),
                    EnableSsl = smtpSection.Network.DefaultCredentials
                };
                var mailMessage = new MailMessage { From = new MailAddress(smtpSection.From, "Paü Dedikodu") };
                mailMessage.To.Add(user.Email);
                mailMessage.Subject = "Paudedikodu.com - Şifre sıfırlama";
#warning akif- link düzeltielecek. mail gönderme common service'e alınacak
                mailMessage.Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Views/Shared/Mail/_RememberPassword.html")).Replace("{0}","link");
                mailMessage.IsBodyHtml = true;
                smtpClient.Send(mailMessage);

                return new Result { IsTrue = true, Message = "Şifre sıfırlama linkiniz mail adresinize gönderildi." };
            }
            catch (Exception)
            {
                return new Result { IsTrue = false, Message = "Bir hata oluştu" };
            }
        }

Asp.net resimli mail gönderme

Using the code

The following code is self explanatory. Here, we go:
  1. Create a string that contains the HTML message to send.
  2. Create an AlternateView object for supporting the HTML.
  3. Create a LinkedResource object for the image to send.
  4. Add a LinkedResource object to the AlternateView object.
  5. Create a Mailmesasge object and set its To, From, and Subject properties.
  6. Add an AlternateView object to the MailMessage object.
  7. Create an SmtpClient object and send the MailMessage object.
using System.Net.Mail;

string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:Pic1\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);


// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);

// Address and send the message
m.From = new MailAddress("rizwan@dotnetplayer.com", "Rizwan Qureshi");
m.To.Add(new MailAddress("shayan@dotnetplayer.com", "Shayan Qureshi"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.dotnetplayer.com");
client.Send(m);

.net 6 mapget kullanımı

 app.UseEndpoints(endpoints => {     endpoints.MapGet("/", async context =>     {         var response = JsonConvert.Seriali...