C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

BlackListIP control on Serenity platform (.NET Core)

 In the Serenity platform, if you want to block IPs that belong to people you do not want to come from outside in the .net core web project, you can follow the steps below.


1- First, create the IP definition script where you can enter the IP information of the person/company you want to block.

CREATE TABLE [dbo].[BlackList](

[BlackListId] [int] IDENTITY(1,1) NOT NULL,

[IpNumber] [varchar](100) NOT NULL,

[Description] [varchar](100) NULL,

 CONSTRAINT [PK_BlackList] PRIMARY KEY CLUSTERED 

(

[BlackListId] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

) ON [PRIMARY]

GO



2- Then generate the Row, Controller, Enpoint and TypeScript codes for the BlackList table via Serenity.




3- Add the class that allows the detection of the external IP to the project. GetIPNumberService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.Net.Http;

using System.Threading.Tasks;


namespace FercamB2B.Web.Modules.Common.Helpers

{

    public class GetIPNumberService

    {

        private readonly HttpClient _httpClient;


        public GetIPNumberService(HttpClient httpClient)

        {

            _httpClient = httpClient;

        }

        public async Task<string> GetUserIpAsync()

        {

            try

            {

                var response = await _httpClient.GetStringAsync("https://ipv4.icanhazip.com");

                return response.Trim();

            }

            catch

            {

                return null; // IP alınamazsa null döner

            }

        }

        private class IpInfo

        {

            public string Ip { get; set; }

        }

    }

}


4- Add the following method to EndPoint.

   

        [HttpPost]

        public BlackListResponse CheckIfBlacklisted(IDbConnection connection)

        {

            BlackListResponse blackListResponse = new BlackListResponse();

            // Senkron IP alma metodunu kullanın

            var ipAddress = _getIPNumberService.GetUserIpAsync().GetAwaiter().GetResult();


            if (ipAddress == null)

            {

                blackListResponse.Durum = false;

                return blackListResponse; // IP alınamazsa, blacklistte değildir

            }


            var blacklistedIp = connection.TryFirst<MyRow>(q => q

                .SelectTableFields()

                .Where(new Criteria(MyRow.Fields.IpNumber) == ipAddress));

            if(blacklistedIp!=null)

            {

                blackListResponse.Durum = true;

                blackListResponse.IP = ipAddress;

            }

            else

            {

                blackListResponse.Durum = false;

            }


            return blackListResponse;

        }

5- Add the IP control method to Loginpanel.ts.

 this.byId('LoginButton').click(e => {

                e.preventDefault();


                if (!this.validateForm()) {

                    return;

                }

               

                let ipAdresi = "";

                let blacklist = false;

                Parametreler.BlackListService.CheckIfBlacklisted({


                }, response4 => {

                    if (response4.Durum == true) {

                        Q.alert("Your IP address is blacklisted!");

                        blacklist = true;

                        return;

                    }

                    ipAdresi = response4.IP;


                }, { async: false });

                if (blacklist) {

                    return;

                }

                console.log("IP address used for login: " + ipAdresi);

As a result, the system that provides control of the entered IP works healthily in this way.



Office 365 kullanan bir hesap üzerinden c# üzerinden mail gönderimi yaparken 535 5.7.139 Authentication unsuccessful hatası hakkında

Office 365 kullanan bir hesap üzerinden c# üzerinden mail gönderimi yaparken 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant hatası alırsanız Office 365 üzerinde bazı işlemler yapmanız gerekmektedir.

Öncelikle C# kodu: 

 class Program

    {

        static void Main(string[] args)

        {

            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress("serkansonmez16@gmail.com", "Serkan"));

            msg.From = new MailAddress("mailuser@contoso.com", "support");

            msg.Subject = "This is a Test Mail";

            msg.Body = "This is a test message using Exchange OnLine";

            msg.IsBodyHtml = true;


            SmtpClient client = new SmtpClient();

            client.UseDefaultCredentials = false ;

            client.Credentials = new System.Net.NetworkCredential("mailuser@contoso.com", "MailPassword");

            client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)

            client.Host = "smtp.office365.com";

            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            client.EnableSsl = true;

            try

            {

                client.Send(msg);

                //lblText.Text = "Message Sent Succesfully";

            }

            catch (Exception ex)

            {

                //lblText.Text = ex.ToString();

                Console.WriteLine(ex.Message);

                Console.Read();

            }

        }

    }



Power Shell üzerinde yapılacaklar:



Önce Power Shell üzerinde exchange 365'e erişim için link üzerinden aşağıdaki kod çalıştırılır.

1-) https://www.powershellgallery.com/packages/ExchangeOnlineManagement/2.0.5

   PS> Install-Module -Name ExchangeOnlineManagement -RequiredVersion 2.0.5


2- Admin kullanıcısına ait mail adresi girilecek, komutu çalıştırınca kullanıcı şifresini girmek gerekiyor.

Doğru şifreyi girdikten sonra Exchange'e ait tüm komutlar aktif hale geliyor.

    PS>Connect-ExchangeOnline -UserPrincipalName adminmailaddress@contoso.com

3- Domain üzerinde SMTP aktif hale getirilmeli, aşağıdaki komut çalıştırılacak.

    PS> Set-TransportConfig -SmtpClientAuthenticationDisabled $true


4- Gönderim yapılacak mail adresi için SMTP aktif hale getiriliyor.

    PS> Set-CASMailbox -Identity sendingMail@contoso.com -SmtpClientAuthenticationDisabled $false


5- Yukarıdaki işlemleri yapsanız da hata almaya devam edebilirsiniz. Son hatanın düzeltilmesi için 

TLS client gönderim için True yapılıyor.


    PS> Set-TransportConfig -AllowLegacyTLSClients $true

Bilgisayarın çıkış yaptığı internet dış IP'yi bulmak (WhatismyIP.com işlevini görür)

Kullanılan sistemlerde çıkış yaptığınız IP'yi kontrol etmek için aşağıdaki prosedür kullanılabilir. Bu https://www.whatismyip.com/ adresindeki gibi dış IP'yi bulmaya yarar.




 Procedure: 
 private static string GetExternalIp()
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                direction = stream.ReadToEnd();
            }
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("
");            direction = direction.Substring(first, last - first);
            return direction;
        }


Kullanımı: 
         private void button2_IpGoster(object sender, EventArgs e)
        {
            string externalIP =  GetExternalIp();
        }

Visual Studio 2017'de Devexpress 17.2.5 Toolbox görünmüyor

Visual Studio 2017 Toolbox'ı üzerinde Developer Express componentlerini göremiyorsanız aşağıdaki komutu çalıştırmak işini görecektir. (Devexpress'i yeniden kurmanıza gerek kalmaz)

1. Visual Studio 2017'yi kapatın.
2. Yönetici olarak CMD (command) komutunu çalıştırın.
3. Sonra ToolboxCreator.exe'nin bulunduğu dizine
            cd\Program Files (x86)\DevExpress 17.2\Components\Tools 
   komutu ile geçin.
3. ToolboxCreator.exe /INI:toolboxcreator.ini  komutunu çalıştırarak işlemi tamamlayın.

 4. Sonuçta Toolbox üzerinde Devexpress componentleri gözükecektir.


Devexpress ASPxGridview "Value cannot be null. Parameter name : value" design hatası

1.       1. Tasarım aşamasında ASPXGridView nesnesi yerine “Value cannot be null. Parameter name : value” hatası karşımıza geldiğinde 2. adıma geçilir.

                    

2.      2. Projedeki aspx dosyasında hatalı olan Assembly dosyasının register satırı çıkarılmalıdır.  Find and Replace ile sorunlu olan <%@ Register namespace="DevExpress.Web" tagprefix="ASPxGridView" %>  satırı tüm projeden çıkarılır ve sorun giderilir.

k





C Sharp: İstenilen tarihin yılın kaçıncı haftası olduğunu gösteren metot


İstenilen tarihin yılın kaçıncı haftası olduğunu bulmak için aşağıdaki metot kullanılabilir. Framework içindeki Datetime sınıfında olmayan ancak işinize yarayabilecek bir metottur.


public int GetWeekNumber(DateTime dtPassed)
{
 CultureInfo ciCurr = CultureInfo.CurrentCulture;
 int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek,      DayOfWeek.Monday);
 return weekNum;

}


Kullanımı:
int hafta = GetWeekNumber(DateTime.Now);  // 08.05.2014
//hafta= 19 olacaktır 



Devexpress AspxTextBox'ta veri girişi yaparken otomatik olarak büyük harfe çevirmek

Devexpress AspxTextBox'ta veri girişi yaparken, girilen bilgiyi otomatik olarak büyük harfe çevirmek için TextBox'ın Client-Side bölümünde  KeyUp  eventine

      s.SetText(s.GetText().toUpperCase());

yazılmalıdır.


ASP.NET formun otomatik yenilenmesi



ASP.NET'te bir form üzerinden yeni bir form açıldığında, geri dönüşte ilk formun yenilenmesi için 2. forma aşağıdaki kod eklenir.


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body onunload="javascript:window.opener.location.reload();">


Devexpress'te Sayı, Tarih, Alfanümerik format tabloları



Format Specifier
Description
Sample Format String
Sample Output
c or C
The number is converted to a string that represents a currency amount. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision from the current regional options is used.
c2
$1,234.00
e or E
The number is converted to a string of the form "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum if required.
E1
1.2E+003
n or N
The number is converted to a string of the form "-d,ddd,ddd.ddd...", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. Thousand separators are inserted between each group of three digits to the left of the decimal point. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision from the current regional options is used.
n0
1,234
x or X
The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether uppercase or lowercase characters are used for hexadecimal digits greater than 9. The precision specifier indicates the minimum number of digits in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. This format is supported for integral types only.
X8
000004D2

C Sharp, Formdaki tüm Texbox'ların içeriğini silmek


Formdaki tüm Texbox'ların içeriğini silmek için aşağıdaki metodu kullanabilirsiniz. this.Controls[t].GetType().Name karşılığına "TextBox" dışında ComboBox, CheckBox gibi diğer arayüz öğelerini de ekleyebilirsiniz.

 public void TextBoxSil()

Operation is not valid due to the current state of the object.

ASP.NET üzerinde AjaxcontrolToolkit kullandıysanız, kullandığınız ekranda postback yapılırken "Operation is not valid due to the current state of the object.hatasını alabilirsiniz. Bunu önlemenin yolu .NET frameworkteki MaxHttpCollection ayarını değiştirmekten geçiyor. Web config dosyasına aşağıdaki satırları ilave ettiğinizde sorun düzelecektir.



Web Config üzerinde eklemeniz gereken satır:

< appSettings>
     key="aspnet:MaxHttpCollectionKeys" value="2001"/ >
 < /appSettings>

Hata Ekranı:





ASP.NET üzerinde Butonu disable etmek

ASP.NET üzerinde Butona tıklandığında butonun disable edilmesi için aşağıdaki kod aspx dosyasına eklenir.
UseSubmitBehavior="false" OnClientClick="this.disabled=true;this.value = 'Lütfen Bekleyiniz...';"

Devexpress AspxGridView kolonlarda filtre türünü değiştirme (AutoFilterCondition)

Devexpress AspxGridView kolonlarında filtre türünü değiştirmek için grid üzerindeki ilgili kolonda Settings--> AutoFilterCondition = default yerine Contains yapılır.
Böylece ilgili kolon üzerinde arama yapmak istenildiğinde içinde aranılan karakterleri içeren tüm kayıtlar listelenir.

Devepress ASPxGrid üzerinde Delete/İnsert/Update butonunu gizlemek

Devepress ASPxGridView üzerinde kullanıcı bazında Delete/İnsert/Update butonunu gizlemek gerekebilir. Bu işlemi yapmak için aşağıdaki kod kullanılabilir. 





protected void ASPxGridView1_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
        {

          if (e.ButtonType == DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Delete)
                e.Visible = false;
        }

ERROR: The name "UserName" does not exits int the current context? in C sharp

PROBLEM:

ERROR: The name "UserName" does not exits int the current context?

SOLUTION:
The name 'UserName' does not exist in the current context?


1. Left-Click in the "yourUserControl.cs" (solution explorer)

2. Select Properties

3. Change Build Action to "Embededd Resource"

C sharp Türkçe karakter kontrol metodu

Eğer veritabanına Türkçe karakter yazmak istemiyorsanız, aşağıdaki metodu kullanabilirsiniz.

Kullanımı:
_Name += "MAIL_METIN,";
_Values += "'" + Tools.TurkceKarakterleriKaldir(HTMLCode) + "',"; 
public static string TurkceKarakterleriKaldir(string EskiMetin)
{
string YeniMetin = "";
string TurkceKarakterler="şŞçÇüÜİıöÖğĞ";
string YeniKarakterler ="sScCuUIioOgG";
for (int i = 0; i < EskiMetin.Length; i++)
{
bool Varmi = false;
for (int k = 0; k < TurkceKarakterler.Length; k++)
{
if (EskiMetin[i] == TurkceKarakterler[k])
{
YeniMetin += YeniKarakterler[k];
Varmi = true;
break;
}
}
if (!Varmi)
{
YeniMetin += EskiMetin[i];
}
}
return YeniMetin;
}
 

I want to get ASCII value of string in C#, what can I do?

Sample Code:

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

Result:

57 113 117 97 108 105 53 50 116 121 51

How can I get the Selected Item for LookupEdit in C#?

try this:
this.bankaSubeleriIdLookUpEdit.Properties.GetDataSourceValue("IBANNo", this.bankaSubeleriIdLookUpEdit.ItemIndex).ToString();

One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes.

In Microsoft Visual Studio 2005, you rebuild a solution and try to view a Microsoft Windows Form in Design view. When you do this, Design view may not show the Windows Form. Additionally, you may receive the following error message and call stack:

PROBLEM:
One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. TypeLoad failure. Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

at System.Reflection.Module.GetTypesInternal(StackCrawlMark& stackMark)
at System.Reflection.Assembly.GetTypes()
at Microsoft.VisualStudio.Shell.Design.AssemblyObsoleteEventArgs..ctor(Assembly assembly)
at Microsoft.VisualStudio.Design.VSDynamicTypeService.ReloadAssemblyIfChanged(String codeBase)
at Microsoft.VisualStudio.Design.VSDynamicTypeService.CreateDynamicAssembly(String codeBase)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_Assembly()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.Search(String fullName, String typeName, Boolean ignoreTypeCase, Assembly& assembly, String description)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.SearchProjectEntries(AssemblyName assemblyName, String typeName, Boolean ignoreTypeCase, Assembly& assembly)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, ReferenceType refType)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.GetType(ITypeResolutionService trs, String name, Dictionary`2 names)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.FillStatementTable(IDesignerSerializationManager manager, IDictionary table, Dictionary`2 names, CodeStatementCollection statements, String className)
at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)

RESOLUTION:

For more information about the MSDN Code Gallery, visit the following Microsoft Web site:
http://code.msdn.microsoft.com/KB912019

To apply this hotfix, you must have Visual Studio 2005 installed on the computer.

Case Problem in C Sharp: Control can't fall through from one case label to another

PROBLEM:
Control can't fall through from one case label to another 4 each case

String status = (String)Session["Status"];

switch (status)
{
case "Book Pending":

string count1 = wucHSRBookModify1.getCount("Offer Pending", "",
"", "", "");
int intcount1 = Convert.ToInt16(count1);
if (intcount1 < 1)
{
wucHSRBookModify1.UpdateBookStatus((String)Session["Status"]);
}

case "Modification Pending":

string count2 = wucHSRBookModify1.getCount("Offer Pending", "Book Pending",
"", "", "");
int intcount2 = Convert.ToInt16(count2);
if (intcount2 < 1)
{
wucHSRBookModify1.UpdateBookStatus((String)Session["Status"]);
}
case "Availability Pending":

string count3 = wucHSRBookModify1.getCount("Offer Pending", "Book Pending",
"Modification Pending", "", "");
int intcount3 = Convert.ToInt16(count3);
if (intcount3 < 1)
{
wucHSRBookModify1.UpdateBookStatus((String)Session["Status"]);
}
}


RESOLUTION:
You need to insert a break; at the end of each case before another case begins.

BlackListIP control on Serenity platform (.NET Core)

 In the Serenity platform, if you want to block IPs that belong to people you do not want to come from outside in the .net core web project,...