<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Sinan Bir Blog</title><link>https://sinanbir.com/</link><description>Developer Soul</description><language>en</language><atom:link href="https://sinanbir.com/feed/" rel="self" type="application/rss+xml"/>
<item><title>TLS Communication Error In a Docker Container</title><link>https://sinanbir.com/tls-communication-error-in-a-docker-container/</link><guid isPermaLink="true">https://sinanbir.com/tls-communication-error-in-a-docker-container/</guid><pubDate>Sun, 11 Jul 2021 17:30:32 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<h2>Problem</h2>


<p>This weekend, I came across with an awkward error that I was not able to access https urls or ssl/tls based services while I was able to access non-tls based services over tcp without any problem inside a container. </p>


<p> First, I taught it was a TLS communication error and start digging around container image base, configurations, ca certificates and etc... But nothing worked. I was right it was a TLS communication error but not at the process level. Before I got into this error, I set up <a href="https://www.wireguard.com/" rel="noreferrer noopener" target="_blank">Wireguard</a> Vpn which I added recently into my setup. So I stop working around wiring new container files and changed my way to other part of the setup.</p>


<hr class="wp-block-separator">


<h2>Solution</h2>


<p>The setup that my docker daemon was running on a host which was configured with <a href="https://www.wireguard.com/">Wireguard</a> VPN. So I started troubleshooting on the network stack and boom...</p>


<pre class="wp-block-code" tabindex="0"><code>~# ip link</code></pre>


<pre class="wp-block-code" tabindex="0"><code>X: wg0: &lt;POINTOPOINT,NOARP,UP,LOWER_UP&gt; mtu <strong>1420</strong> qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/none
X: docker0: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu <strong>1500</strong> qdisc noqueue state DOWN mode DEFAULT group default
    link/ether XX:XX:XX:XX:XX:XX brd ff:ff:ff:ff:ff:ff</code></pre>


<p>The problem was because of different MTU sizes on the docker and wg* interfaces. </p>


<p>The Docker Daemon does not check the MTU size of the any available network interfaces. Therefore, the value of the Docker MTU was set to 1500. When I change MTU size of docker0 interface to 1420 that matches the wireguard default MTU size, everything started working again.</p>


<h3>Wireguard Docker Repository</h3>


<p>It is also mentioned under others section on the repository.</p>


<blockquote class="wp-block-quote"><p>For some clients (a GL.inet router in my case) you may have trouble with HTTPS (SSL/TLS) due to the MTU on the VPN. Ping and HTTP work fine but HTTPS does not for some sites.</p><p> This can be fixed with&nbsp;<a href="https://www.tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.cookbook.mtu-mss.html" rel="noreferrer noopener" target="_blank">MSS Clamping</a>. This is simply a checkbox in the OpenWRT Firewall settings interface.</p><cite><a href="https://github.com/cmulk/wireguard-docker" rel="noreferrer noopener" target="_blank">https://github.com/cmulk/wireguard-docker</a></cite></blockquote>


<p>You can find more information on  wireguard-docker repository.</p>


<h2>Docker Daemon Configuration</h2>


<pre class="wp-block-code" tabindex="0"><code>/etc/docker/daemon.json</code></pre>


<pre class="wp-block-code" tabindex="0"><code>{
  "mtu": 1420
}</code></pre>


<p>Restart the docker daemon and we are all set. If the output of MTU size doesn't update suddenly, make sure you have run a container after the configuration. </p>]]></content:encoded></item>
<item><title>Asynchronous Server Application Example - Java</title><link>https://sinanbir.com/java-async-server-socket-example/</link><guid isPermaLink="true">https://sinanbir.com/java-async-server-socket-example/</guid><pubDate>Fri, 27 Mar 2020 21:40:57 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<h1>Async Server</h1><p>
Asynchronous server application is not suspended while it waits for a connection from a client. If we spin up threads for each session, then the server waits for the IO operations which we don't want. This example project shows handling tcp sockets&nbsp;Asynchronously without running separate threads for each session.

The example async socket server is available on <a href="https://github.com/deluxetiky/java-async-socket-server" rel="noopener" target="_blank">github</a>.


</p><h2>Getting Started</h2>
<p><strong>Requirements</strong>
</p><ul>
<li>Java 8</li>
<li>Maven</li>
</ul>
<h3>Project Setup</h3>
<h4>1. Clone Repository</h4>
<pre class="lang:default decode:true" tabindex="0" title="git clone">git clone https://github.com/deluxetiky/java-async-socket-server
cd java-async-socket-server</pre>
<h4>2. Build Project</h4>
<pre class="lang:sh decode:true" tabindex="0" title="compile">mvn compile</pre>
<pre class="theme:solarized-dark lang:sh decode:true" tabindex="0">[INFO] 
[INFO] ----------------&lt; org.example:java-async-socket-sample &gt;----------------
[INFO] Building java-async-socket-sample 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-async-socket-sample ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ java-async-socket-sample ---
[INFO] Nothing to compile - all classes are up to date
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS</pre>
<h4>3. Spin-Up Server</h4>
<pre class="lang:sh decode:true" tabindex="0">mvn exec:java -Dexec.mainClass="Server.SocketStandAlone"</pre>
<pre class="theme:solarized-dark lang:default decode:true" tabindex="0">[INFO] 
[INFO] ----------------&lt; org.example:java-async-socket-sample &gt;----------------
[INFO] Building java-async-socket-sample 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ java-async-socket-sample ---
2020-03-27 21:16:39 INFO  SocketServer:30 - Device socket server started on /0.0.0.0:5050</pre>
<h4>4. Finish</h4><p>
We can spin up multiple concurrent sessions with telnet. Our server will be pushing back to same data that we sent.
</p><pre class="lang:sh decode:true" tabindex="0">telnet localhost 5050</pre><p>
Project <a href="https://github.com/deluxetiky/java-async-socket-server" rel="noopener" target="_blank">repository.</a>

That was a quick one. So hope I will come back and explain the code in the repository more detailed.

&nbsp;

&nbsp;</p>]]></content:encoded></item>
<item><title>Apache Flink Stateful Streaming Example</title><link>https://sinanbir.com/apache-flink-stateful-streaming-example/</link><guid isPermaLink="true">https://sinanbir.com/apache-flink-stateful-streaming-example/</guid><pubDate>Sun, 26 Aug 2018 00:16:48 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<h1>Apache Flink Stateful Streaming</h1><p>
Today, We will create simple Apache Flink stateful streaming word count application to show you up how powerful apis it has and easy to write stateful applications. Stream processing is one of the most important component of modern data driven application pipelines. There is a nice article <a href="https://www.infoworld.com/article/3267966/big-data/stateful-stream-processing-with-apache-flink.html" rel="noopener" target="_blank">here</a> which is more about the use cases, stateful term definitions and business values of it. In this article I want to focus more on stateful scenario .


</p><figure class="wp-caption"><img alt="Flink Architecture" decoding="async" height="688" loading="lazy" src="https://flink.apache.org/img/usecases-eventdrivenapps.png" title="Flink Architecture Stateful Streaming" width="2336"><figcaption>Flink Architecture Comparison with Traditional Pipelines</figcaption></figure><p>

This picture shows really nice how its architecture differs from traditional application pipelines.

There are not many examples to the Flink on the internet. That's why I decided to write this article. Especially, for the stateful streaming part, tons of papers are around... Okay it's enough for the intro, let's get hands on dirty...
</p><h2>Sample Scenario</h2><p>
In this example, I will create word count stream analytics pipeline which has two inputs that are used for data ingestion and dynamic filtering. While one input ingests stream of words, the other sets the filtering criteria of the the pipeline dynamically. The input filter stream updates the current state in the co-process function where our logic is implemented. After joining two streams together, the co-process function applies filtering condition based on the state updated with the input&nbsp;filter stream. Afterwards, we'll apply sliding window function that has 5 seconds size with 1 second sliding interval. The result of all this pipeline goes into one output sink which is tcp socket connection in our case.

<a href="/wp-content/uploads/2018/08/stream-pipeline-2.png"><img alt class="alignnone wp-image-524 size-full" decoding="async" height="361" loading="lazy" src="/wp-content/uploads/2018/08/stream-pipeline-2.png" width="1229"></a>
</p><h2><strong>Project Setup
</strong></h2><p>
You can set up Flink environment quickly by visiting <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.6/quickstart/setup_quickstart.html" rel="noopener" target="_blank">this link.</a>After you complete that step, we are ready to create our project. I'll use maven quick start template
</p><pre class="font-size:14 line-height:17 lang:sh decode:true" tabindex="0">$mvn archetype:generate -DarchetypeGroupId=org.apache.flink \
-DarchetypeArtifactId=flink-quickstart-java \
-DarchetypeVersion=1.6.0 \
-DgroupId=com-streaming-example \
-DartifactId=com-streaming-example \
-Dversion=1.0 \
-Dpackage=com.sinanbir.example</pre><p>
After this step, our project basic structure will be ready for us.

We will be using Rocks Db state backend. It's not added as a default package in quick start template. So, to use this package you should add it to your dependencies by adding following line into <strong>pom.xml</strong>
</p><pre class="lang:default decode:true" tabindex="0" title="RocksDb State backend package">&lt;dependencies&gt;
  ...	
    &lt;dependency&gt;
			&lt;groupId&gt;org.apache.flink&lt;/groupId&gt;
			&lt;artifactId&gt;flink-statebackend-rocksdb_2.11&lt;/artifactId&gt;
			&lt;version&gt;1.6-SNAPSHOT&lt;/version&gt;
    &lt;/dependency&gt;
  ...
&lt;/dependencies&gt;</pre><p>
After we complete the setup above. The project structure will be like in the picture.

<a href="/wp-content/uploads/2018/08/project-structure.png"><img alt="project structure" class="alignnone size-full wp-image-505" decoding="async" height="607" loading="lazy" src="/wp-content/uploads/2018/08/project-structure.png" width="393"></a>
</p><h2>Application Code</h2>
<pre class="top-margin:20 lang:java decode:true" tabindex="0" title="StreamingJob.java">public class StreamingJob{

	public static void main(String[] args) throws Exception{

		final ParameterTool params = ParameterTool.fromArgs(args);
		int portWordStream = params.getInt("portStream");
		int portFilterStream = params.getInt("portFilterStream");
		int portSink = params.getInt("portSink");
		String stateDir = params.get("stateDir");
		String socketHost = params.get("host");

		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
		env.setStateBackend(new RocksDBStateBackend(stateDir, false));
		env.enableCheckpointing(2000);// start a checkpoint every 2seconds
		CheckpointConfig config = env.getCheckpointConfig();
		config.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);// set mode to exactly-once (this is the default)
		config.enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

		DataStream&lt;Tuple2&lt;String,Integer&gt;&gt; wordStream = env
				.socketTextStream(socketHost, portWordStream).name("Word Stream")
				.setParallelism(1)
				.flatMap(new WordStreamParser()).name("Word FlatMap")
				.keyBy(0);

		DataStream&lt;Tuple2&lt;String,Boolean&gt;&gt; filterStream = env
				.socketTextStream(socketHost, portFilterStream).name("Filter Stream")
				.setParallelism(1)
				.flatMap(new FilterStreamParser()).name("Filter FlatMap")
				.keyBy(0);

		DataStream&lt;Tuple2&lt;String,Integer&gt;&gt; joinedStream = wordStream
				.connect(filterStream)
				.process(new JoinProcessFunction()).setParallelism(5).uid("join-1").name("Co-JoinProcess")
				.keyBy(0)
				.window(SlidingProcessingTimeWindows.of(Time.seconds(5), Time.seconds(1)))
				.sum(1).name("Summarize")
				.setParallelism(5);

		joinedStream.map((MapFunction&lt;Tuple2&lt;String,Integer&gt;,String&gt;)input -&gt; String.format("%tT | %s Count: %d\
", LocalDateTime.now(), input.f0, input.f1))
				.returns(String.class)
				.writeToSocket(socketHost, portSink, new SimpleStringSchema())
				.setParallelism(1)
				.name("Socket Output");


		// execute program
		env.execute("Flink Streaming Stateful Java Example");
	}
}</pre><p>
Between line 14-18 we configured our application to keep its state at file system with Rocksdb state backend. I set the check interval 2 seconds for test purposes.&nbsp; At line 18, we specified that even we cancelled the job, state should be retained. I kept the state cause I'll show you how to re-deploy application that continuous from existing state.&nbsp; I won't go details of this configurations too much because more detailed different settings depend on your program flow. The important part here is that we set explicitly we want to keep our state at the file system with a Rocksdb state backend. Further information can be found <a href="https://flink.apache.org/features/2018/01/30/incremental-checkpointing.html" rel="noopener" target="_blank">here.</a>

&nbsp;

The rest of the code defines how our pipeline process events. I wanna mention some important part here, at the end of some functions I set parallelism explicitly. For example, at the first stage of our code&nbsp; I set parallelism to one cause I will use <strong>netcat</strong> for the socket listening part and It can not listen tcp connections in broker mode. If the source was different like Kafka, it wouldn't be problem.&nbsp; It is similar for the output socket sink.
</p><blockquote><strong>Note: </strong>If you deploy an application that requires more task resources than the cluster has, deployment stucks at starting. I had similar problem when I want to deploy an app unless I change the <strong>taskmanager.numberOfTaskSlots </strong>number more than my application requirements in the <strong>flink-conf.yaml.</strong></blockquote><p>
An other important point is we set the event time to <strong>ProcessingTime </strong>which is directly related with our windowing function selection. We used <strong>SlidingProcessingTimeWindows </strong>which doesn't work with <strong>EventTime. </strong>However, we can still override watermark settings with custom implementation to overcome this but this is not necessary in our example.

&nbsp;

In this example, there are two different flat-map implementation which are mapping socket text stream data to flink's tuple class type.The type Tuple is preferred just for development purposes. If you want, you can implement your own custom POJOs.
</p><pre class="tab-size:6 lang:java decode:true" tabindex="0" title="WordStreamParser.java">public class WordStreamParser implements FlatMapFunction&lt;String,Tuple2&lt;String,Integer&gt;&gt;{
	@Override
	public void flatMap(String s, Collector&lt;Tuple2&lt;String,Integer&gt;&gt; collector) throws Exception{
		for(String word : s.trim().split(" ")) {
			collector.collect(Tuple2.of(word, 1));
		}
	}
}</pre><p>
Here, we split string to words and assign each word 1.
</p><pre class="tab-size:6 lang:java decode:true" tabindex="0" title="FilterStreamParser.java">public class FilterStreamParser implements FlatMapFunction&lt;String,Tuple2&lt;String,Boolean&gt;&gt;{
	@Override
	public void flatMap(String s, Collector&lt;Tuple2&lt;String,Boolean&gt;&gt; collector) throws Exception{
		String[] strVals = s.split("=");
		if(strVals.length == 2){
			String key = strVals[0];
			Boolean val = strVals[1].equals("1") || strVals[1].equals("true");
			collector.collect(Tuple2.of(key, val));
		}
	}
}</pre><p>
Here we defined a scheme that works only when the input is in the format of

-&gt; word=0

-&gt; word=1

-&gt; word=true

Now it's time to explain how are we going to join these two streams together while we keep the current state sync. Let me explain this with the code
</p><pre class="lang:java decode:true" tabindex="0" title="JoinProcessFunction.java">public class JoinProcessFunction extends CoProcessFunction&lt;Tuple2&lt;String,Integer&gt;,Tuple2&lt;String,Boolean&gt;,Tuple2&lt;String,Integer&gt;&gt;{
	private ValueState&lt;FilterState&gt; state;

	@Override
	public void open(Configuration parameters) throws Exception{
		ValueStateDescriptor&lt;FilterState&gt; desc = new ValueStateDescriptor&lt;&gt;(
				"filterState",
				FilterState.class, new FilterState(true)
		);
		state = getRuntimeContext().getState(desc);
	}

	@Override
	public void processElement1(Tuple2&lt;String,Integer&gt; input, Context context, Collector&lt;Tuple2&lt;String,Integer&gt;&gt; collector) throws Exception{
		String key = input.f0;
		FilterState current = state.value();
		if(current.Active) collector.collect(input);//filtering place
	}

	@Override
	public void processElement2(Tuple2&lt;String,Boolean&gt; input, Context context, Collector&lt;Tuple2&lt;String,Integer&gt;&gt; collector) throws Exception{
		FilterState current = state.value();
		current.Active = input.f1;//set state value
		state.update(current);
	}
}</pre><p>
The co-process function is bound two different inputs. In our case, processElement1 is called whenever we receive an event from word stream socket and it checks whether the word is activated or not. The function class manages the life cycle of the state. Before we connected two stream together we called keyBy function to distribute tasks based on the key which is word. When we called state.value() we get state of the key that we set with the keyBy. Second input ( filter stream ) only updates the state itself. It doesn't emit any data.This is really nice capability. You can implement any low level join or other stateful processing functions. The flink api itself takes care of distributing the state among the task managers. So you just focus on your application business logic. More detailed information can be found <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.6/dev/stream/operators/process_function.html" rel="noopener" target="_blank">here.</a>
</p><h2>Deployment & Running</h2><p>
So far, we've have explained what is our application about and mentioned some apis of the Flink. Now, we'll deploy and run our application. We'll use flink cli to deploy and run our application after we compiled application artifacts.
</p><pre class="lang:default decode:true" tabindex="0">mvn package</pre><p>
It will build <strong>com-streaming-example-1.0.jar </strong>file in the target directory.

Before sending our job to flink we need to open socket listeners. I'll use netcat tool for the running tcp listener on my local environment.
</p><pre class="lang:default decode:true" tabindex="0" title="Netcat Listeners">nc -L localhost -p &lt;port&gt; // filter stream
nc -L localhost -p &lt;port&gt; // word stream
nc -L localhost -p &lt;port&gt; // output sink

</pre><p>
After we run our tcp listeners, we can send our application to flink local cluster with command below. In my demo I preferred port 9002, 9003 and 9004.
</p><pre class="wrap:true lang:default decode:true" tabindex="0">bin\flink run -c com.sinanbir.example.StreamingJob &lt;com-streaming-example-1.0.jar - Path&gt;  --portStream &lt;port&gt; --portFilterStream &lt;port&gt; --portSink 9004 --host &lt;host&gt;  --stateDir &lt;statedirectory path file:///&gt;</pre>
<p><a href="/wp-content/uploads/2018/08/jobsubmitresult.png"><img alt="stateful streaming" class="alignnone wp-image-528 size-full" decoding="async" height="985" loading="lazy" src="/wp-content/uploads/2018/08/jobsubmitresult.png" width="1915"></a>

Now our job has been submitted successfully.&inodot;f your application doesn't start, make sure that all of the listeners are working properly.

Now,It's time to test our stream pipeline.

<a href="/wp-content/uploads/2018/08/output-with-time-1.png"><img alt class="alignnone wp-image-532 size-full" decoding="async" height="1022" loading="lazy" src="/wp-content/uploads/2018/08/output-with-time-1.png" width="1912"></a>

As you can see the words which have been disabled are not buffered to window summarize function and sliding window results are as expected.

In an other article I'll show an example of how to redeploy an existing application and run it from its previous state.

You can access all of the code base from <a href="https://github.com/deluxetiky/flink-streaming-example" rel="noopener" target="_blank">here.</a>

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;</p>]]></content:encoded></item>
<item><title>Continuous Integration &amp; Delivery vs Deployment</title><link>https://sinanbir.com/continuous-delivery-vs-deployment/</link><guid isPermaLink="true">https://sinanbir.com/continuous-delivery-vs-deployment/</guid><pubDate>Mon, 18 Dec 2017 01:02:10 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[&nbsp;
<h2>Continuous Integration</h2><p>
&nbsp;

It is the practice that requires developers to integrate the code into a shared repository at least once a day. The integration is followed up by a build and test steps to solve problems quickly. Then you can fix the problems easily before they get serious. It would be hard to find and fix them on the repository where the developers don't integrate their changes so often. When they do, they will be able to add new features instead of spending more time on debugging. Everyone can see what is happening on the repository. Unit and Integration tests have important roles on that pipeline. Overall, reduced risks, release more often and provide higher quality products.
</p><blockquote>
<h2 class="heading__section">&ldquo;Continuous Integration doesn&rsquo;t get rid of bugs, but it does make them dramatically easier to find and remove.&rdquo;</h2>
<h3>&mdash; Martin Fowler, Chief Scientist, ThoughtWorks</h3>
</blockquote>
<p><a href="/wp-content/uploads/2017/12/continuous-integration.png"><img alt="continuous integration" class="wp-image-490 aligncenter" decoding="async" height="443" loading="lazy" src="/wp-content/uploads/2017/12/continuous-integration.png" width="475"></a>
</p><h2>Continuous Delivery vs Deployment</h2><p>
Satisfying customers feedback on the production is important. Continuous Delivery is the discipline where the software can be released to production when there is a change on the code&nbsp; or configuration. Your application can benefit from this while providing you always production ready software. So what is the difference between delivery and the deployment ? Continuous delivery is the pipeline where the release is controlled manually whereas continuous deployment is the pipeline which is sequences of automated steps. The changes are always released to the production in continuous deployment. However it requires continuous delivery. So they are the terms which are&nbsp;used for each other by mistake.

<a href="/wp-content/uploads/2017/12/cdvscd1.png"><img alt="continuous depyloyment vs delivery" class="size-full wp-image-488" decoding="async" height="596" loading="lazy" src="/wp-content/uploads/2017/12/cdvscd1.png" width="1482"></a><span class="st-9acc68">CD vs CI</span>

&nbsp;

&nbsp;</p>]]></content:encoded></item>
<item><title>.Net Core 2 IdentityServer4 Example - OpenId OAuth2</title><link>https://sinanbir.com/identityserver4-netcore-refresh-token-example/</link><guid isPermaLink="true">https://sinanbir.com/identityserver4-netcore-refresh-token-example/</guid><pubDate>Fri, 03 Mar 2017 18:47:36 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>Since .netCore released I couldn't find much information about how to implement either oauth2 or openId .I found identityServer4 easy to create an authorization server and did an example how to set it up. I hope this article will be helpful for some who is looking for what it is and how to implement identityserver4 along with refreshtoken on the .net core 2. So,what is IdentityServer4 ?&nbsp;IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core. It is free and also has support for&nbsp;commercial uses.We'll be creating hybrid authentication flow to implement refresh token using grant types Resource Owner Password Credentials(ROPC) and Refresh Token. &nbsp;I won't be explaining all protocols here. If you need further information you can checkout <a href="http://docs.identityserver.io/en/release/#">IdentityServer4</a>&nbsp; ,<a href="https://oauth.net/2/">OAuth2</a>&nbsp;and <a href="http://openid.net/get-an-openid/what-is-openid/">OpenId</a>. Let's dig into some coding.


</p><h3>Setup Projects</h3><p>
I will be using Visual Studio 2017 as my IDE. &nbsp;You need .netCore framework installed before. Later on, we are going to test our identity api with my favorite tool PostMan.
</p><ul>
<li>Lets create our .netCore api project.<a href="/wp-content/uploads/2017/03/createproject1.png"><img alt class="alignnone size-full wp-image-438" decoding="async" height="677" loading="lazy" src="/wp-content/uploads/2017/03/createproject1.png" width="977"></a></li>
<li>Then select empty template</li>
<li>In<strong> program.cs</strong> file add
<blockquote><span class="n">UseUrls</span><span class="p">(</span><span class="s">"http://localhost:8000"</span><span class="p">)</span></blockquote>
</li>
</ul><p>
Install Identity Server package "Abp.ZeroCore.IdentityServer4" with nuget package manager. After installation you will have package reference in your csproj file like below.
</p><ul>
<li>
<blockquote>&nbsp; &lt;ItemGroup&gt;
&lt;PackageReference Include="Abp.ZeroCore.IdentityServer4" Version="3.2.5" /&gt;
&lt;PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" /&gt;
&lt;/ItemGroup&gt;</blockquote>
</li>
</ul>
&nbsp;
<ul>
<li>We are going to configure IdentityServer to use MemoryStore for test purposes. In production you shouldn't use it in that way. Let's create <strong>MemoryDb.cs</strong> file to store our client and resource information. IdentityServer also has support for EF. More information could be found on identity server <a href="http://docs.identityserver.io/en/release/reference/ef.html">website</a>.
<pre class="left-set:true lang:c# decode:true" tabindex="0">using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;

namespace WebApp.IdentityServer.Example.Helper
{
	public class MemoryDb
	{
		// scopes define the API resources in your system
		public static IEnumerable&lt;ApiResource&gt; GetApiResources()
		{
			return new List&lt;ApiResource&gt;
			{
				new ApiResource("sinanbir.com.auth", "My API Display Name")
			};
		}

		// clients
		public static IEnumerable&lt;Client&gt; GetClients()
		{
			// client credentials client
			return new List&lt;Client&gt;
			{
				new Client
				{
					ClientId = "client1",
					AllowedGrantTypes = GrantTypes.ClientCredentials,

					ClientSecrets =
					{
						new Secret("password".Sha256())
					},
					AllowedScopes = { "sinanbir.com.auth" }
				},
 
                // resource owner password grant client
                new Client
				{
					ClientId = "ropcclient",
					AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
					AllowOfflineAccess = true,//Enables refresh token.
                    ClientSecrets =
					{
						new Secret("password".Sha256())
					},
					AllowedScopes = { "sinanbir.com.auth", IdentityServerConstants.StandardScopes.OfflineAccess, }
				}
			};
		}

		public static List&lt;TestUser&gt; GetUsers()
		{
			return new List&lt;TestUser&gt;
			{
				new TestUser
				{
					SubjectId = "1",
					Username = "sinan",
					Password = "bir"
				},
				new TestUser
				{
					SubjectId = "2",
					Username = "testuser",
					Password = "password"
				}
			};
		}
	}
}
</pre>
<strong>"ropcclient"</strong> will be able to use&nbsp;refresh token by adding <strong>IdentityServerConstants.StandardScopes.OfflineAccess</strong> to its allowed scopes. You will get invalid scope error if you don't specify this scope.<strong> It's important!</strong>

&nbsp;</li>
</ul><p>
Lastly, We should modify our <strong>startup.cs</strong> file to run server and token validation. If you're migrating from asp.net core <strong>1.x to 2.x</strong> some functions get replaced. Before 2.x release we were able to use <strong>app.<span class="st-d1fff9">UseIdentityServerAuthentication</span> </strong>method in Configure section but it's replaced with <strong>app.UseAuthentication</strong> method. Identity server will be enabled after adding&nbsp;<strong>app.UseIdentityServer</strong> method in <strong>Configure</strong> section.

It requires some service configurations before setting up server. We will be registering Memory implemented class into services pipeline.
</p><blockquote>services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(MemoryDb.GetApiResources())
.AddInMemoryClients(MemoryDb.GetClients())
.AddTestUsers(MemoryDb.GetUsers());</blockquote><p>
The first method <strong>AddIdentityServer</strong> adds default IdentiyServer services to the DI system.

<strong>AddDeveloperSigningCredential</strong> method adds temporary key at&nbsp; startup. If you don't have certificate it's easy for testing purposes.

<strong>AddInMemoryApiResources</strong> method adds our memory implementation resources to identity server settings.

<strong>AddInMemoryClients&nbsp;</strong>method adds our memory client to the identity server.

<span class="st-35868d"> <strong><span class="st-944b7c">AddTestUsers</span></strong></span> adds memory users to the server. If you want to change memory implementation of the user store, you should call <strong>AddAspNetIdentity&lt;User&gt;</strong> method. It will be looking for the service <strong>IUserStore&lt;User&gt;</strong>.

&nbsp;

After registering dependencies into DI service, we'll be setting <strong>JWT Bearer</strong> options in <strong>ConfigureServices</strong> section for token validation. This settings will be used to validate our JWT token. If you're setting up a seperate identity server you don't have to configure this part. It will be only responsible to validating our tokens. First part is enough to setup our identity server for implementing openid and oauth2. But in our example we won't be setting up separate auth and api projects. So we'll be implementing them together in one solution.

After completing the steps above you will have a <strong>startup.cs&nbsp;</strong>
</p><pre class="left-set:true lang:c# decode:true" tabindex="0" title="Startup.cs">using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using WebApp.IdentityServer.Example.Helper;

namespace WebApp.IdentityServer.Example
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


			var authUrl = "http://localhost:8000";

			#region IdentityServerSetup

			services.AddIdentityServer()
				.AddDeveloperSigningCredential()
				.AddInMemoryApiResources(MemoryDb.GetApiResources())
				.AddInMemoryClients(MemoryDb.GetClients())
				.AddTestUsers(MemoryDb.GetUsers());

			#endregion

			#region Validation Settings
			services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
			.AddJwtBearer(options =&gt;
			{
				options.Authority = authUrl;
				options.RequireHttpsMetadata = false;
				options.TokenValidationParameters = new TokenValidationParameters
				{
					ValidateIssuer = true,
					ValidIssuer = authUrl,
					ValidateAudience = false,
					ValidAudience = "sinanbir.com.auth",//test purposes
					ValidateLifetime = true,
				};
			});

			#endregion
			services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

			
			app.UseIdentityServer();
			app.UseAuthentication();
			app.UseMvc();
        }
    }
}
</pre><p>
Now our server is ready for both providing tokens and validating them.
</p><h3><strong>Testing Server</strong></h3><p>
Let's test our server. If you did all steps&nbsp;above properly then you should be able to see our server configuration by doing get request to&nbsp;<strong>http://localhost:8000/.well-known/openid-configuration&nbsp;</strong>end-point.
</p><pre class="lang:js decode:true" tabindex="0" title="response">{
  "issuer": "http://localhost:8000",
  "jwks_uri": "http://localhost:8000/.well-known/openid-configuration/jwks",
  "authorization_endpoint": "http://localhost:8000/connect/authorize",
  "token_endpoint": "http://localhost:8000/connect/token",
  "userinfo_endpoint": "http://localhost:8000/connect/userinfo",
  "end_session_endpoint": "http://localhost:8000/connect/endsession",
  "check_session_iframe": "http://localhost:8000/connect/checksession",
  "revocation_endpoint": "http://localhost:8000/connect/revocation",
  "introspection_endpoint": "http://localhost:8000/connect/introspect",
  "frontchannel_logout_supported": true,
  "frontchannel_logout_session_supported": true,
  "scopes_supported": [
    "myApi",
    "offline_access"
  ],
  "claims_supported": [],
  "response_types_supported": [
    "code",
    "token",
    "id_token",
    "id_token token",
    "code id_token",
    "code token",
    "code id_token token"
  ],
  "response_modes_supported": [
    "form_post",
    "query",
    "fragment"
  ],
  "grant_types_supported": [
    "authorization_code",
    "client_credentials",
    "refresh_token",
    "implicit",
    "password"
  ],
  "subject_types_supported": [
    "public"
  ],
  "id_token_signing_alg_values_supported": [
    "RS256"
  ],
  "token_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "client_secret_post"
  ],
  "code_challenge_methods_supported": [
    "plain",
    "S256"
  ]
}</pre><p>
The postman collection that I've used for tests can be reached <a href="https://www.getpostman.com/collections/bd3f5eca578409b68791">from here.</a>
</p><figure class="wp-caption"><img alt="token refresh oauth2 openid" class="wp-image-472 size-full" decoding="async" height="889" loading="lazy" src="/wp-content/uploads/2017/03/postmancore2-1.png" width="1541"><figcaption>Token Request</figcaption></figure>
<h2>RefreshToken Test</h2><p>
We'll be renewing our token for the next request by changing the grant type password to refresh_token along with the refresh_token that we get from this request.

</p><figure class="wp-caption"><img alt="refresh token openid oauth2" class="wp-image-473 size-full" decoding="async" height="853" loading="lazy" src="/wp-content/uploads/2017/03/postmancore2-3.png" title="identityserver4 refresh token example" width="1525"><figcaption>Refresh Token Request</figcaption></figure><p>

The repo which I created for this article can be reached from <a href="https://github.com/deluxetiky/WebApp.IdentityServer.Example">here.</a>

&nbsp;

That's it. It's just quick setup to show how easy it is with IdentityServer. If you are looking for more samples, you can check out github <a href="https://github.com/IdentityServer/IdentityServer4">repo</a>.

&nbsp;</p>]]></content:encoded></item>
<item><title>Simpson's 3 8 Method C Code - Integration</title><link>https://sinanbir.com/simpsons-3-8-method-c-code/</link><guid isPermaLink="true">https://sinanbir.com/simpsons-3-8-method-c-code/</guid><pubDate>Sat, 28 May 2016 19:50:57 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<h2>Simpson's 3 8 Method C Code</h2><p>
I will share the Simpson's 3 8 Method C Code. There are other methods that can calculate the integration more accurate&nbsp;but today I'll share one of my class notes which can be helpful who is looking for an easy implementation of this method.&nbsp;The function that I use for this program is e<sup>x</sup> whose integration is same as itself. You can implement your custom function easily overriding &nbsp;f(double x) prototype. Program requires lower, upper bound of integration and the n ( part count ) as an input. You can get more accurate results when you give n is high enough. Because the method is applied each part independently. You can check out code of the program below.&nbsp;The method detailed <a href="https://en.wikipedia.org/wiki/Simpson%27s_rule">information</a>.


</p><pre class="lang:c decode:true" tabindex="0" title="C Code of Method">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#define _USE_MATH_DEFINES
#include &lt;math.h&gt;


double  lower,upper;
int step;

double f(double x);
double simpson(double lower, double upper);
int main() {
	printf("Please enter lower bound:");
	scanf("%lf", &lower);
	printf("Please enter upper bound:");
	scanf("%lf", &upper);
	printf("Please enter n:");
	scanf("%d", &step);
	double result=0;
	
	double functionIncrement= (upper - lower)/ step;
	
	for (int i = 0; i &lt; step; i++)
	{
		double low = lower + i*functionIncrement;
		double up = low + functionIncrement;
		result += simpson(low, up);
		printf("%lf %lf\
", low, up);

	}
	
	printf("Integration result is: %.10lf\
", result);
	system("PAUSE");
	return 0;
}

double f(double x){
	return pow(M_E,x);
}

double simpson(double lower, double upper)//n=3 3/8 kural&inodot;
{
	double h = (upper - lower) / 3;
	double mid = lower + h;
	double mid2 = mid + h;
	double res = (3 * h / 8)*(f(lower) + 3 * f(mid) + 3 * f(mid2) + f(upper)) - 3*pow(h,5)/80;
	return res;
}
</pre><p>
An example output when you run the program above.

Lower Bound : 1

Upper Bound : 4

n : 18

<a href="/wp-content/uploads/2016/05/simpson38result.png"><img alt="simpson's 3 8" class="alignnone wp-image-361 size-full" decoding="async" height="547" loading="lazy" src="/wp-content/uploads/2016/05/simpson38result.png" title="Simpson's 3 8 Method C Code" width="978"></a>

Result of the integration is : 51.8798740205

When you take the original function integration it gives us&nbsp;51.8798682046852.

It shows that&nbsp;fault tolerance is in 4 decimal precision. When we give n : 100

The result becomes more accurate like&nbsp;51.8798682108.</p>]]></content:encoded></item>
<item><title>Lagrange Interpolation C Code</title><link>https://sinanbir.com/lagrange-interpolation/</link><guid isPermaLink="true">https://sinanbir.com/lagrange-interpolation/</guid><pubDate>Thu, 31 Mar 2016 02:12:54 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>In <a href="https://en.wikipedia.org/wiki/Numerical_analysis" title="Numerical analysis">numerical analysis</a>, <b>Lagrange polynomials</b> are used for <a href="https://en.wikipedia.org/wiki/Polynomial_interpolation" title="Polynomial interpolation">polynomial interpolation</a>. For a given set of distinct points <img alt="x_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/f/4/b/f4bb95e27d8505366199bb81f2b75b6f.png"> and numbers <img alt="y_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/f/b/0fb734d9f37222c4626ec4c6c6490ea3.png">, the Lagrange polynomial is the polynomial of the least degree that at each point <img alt="x_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/f/4/b/f4bb95e27d8505366199bb81f2b75b6f.png"> assumes the corresponding value <img alt="y_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/f/b/0fb734d9f37222c4626ec4c6c6490ea3.png"> (i.e. the functions coincide at each point). The interpolating polynomial of the least degree is unique, however, and it is therefore more appropriate to speak of "the Lagrange form" of that unique polynomial rather than "the Lagrange interpolation polynomial", since the same polynomial can be arrived at through multiple methods.



Given a set of <i>k</i>&nbsp;+&nbsp;1 data points
</p><dl>
<dd><img alt="(x_0, y_0),\ldots,(x_j, y_j),\ldots,(x_k, y_k)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/7/6/0767809fac8ae98477202d2f79090ad5.png"></dd>
</dl><p>
where no two <img alt="x_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/f/4/b/f4bb95e27d8505366199bb81f2b75b6f.png"> are the same, the <strong>Lagrange Interpolation</strong><b>&nbsp;form</b> is a <a href="https://en.wikipedia.org/wiki/Linear_combination" title="Linear combination">linear combination</a>
</p><dl>
<dd><img alt="L(x) := \sum_{j=0}^{k} y_j \ell_j(x)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/f/b/f/fbf1a1a198c3f3c6dc043ef8e18f8835.png"></dd>
</dl><p>
of Lagrange basis polynomials
</p><dl>
<dd><img alt="\ell_j(x) := \prod_{\begin{smallmatrix}0\le m\le k\\ m\
eq j\end{smallmatrix}} \frac{x-x_m}{x_j-x_m} = \frac{(x-x_0)}{(x_j-x_0)} \cdots \frac{(x-x_{j-1})}{(x_j-x_{j-1})} \frac{(x-x_{j+1})}{(x_j-x_{j+1})} \cdots \frac{(x-x_k)}{(x_j-x_k)}," class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/1/e/4/1e439bae00050b2e5a6045e9b3677072.png"></dd>
</dl><p>
where <img alt="0\le j\le k" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/8/e/d/8edf123c37910d6ad1fae0329f07ab16.png">. Note how, given the initial assumption that no two <img alt="x_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/5/e/05e42209d67fe1eb15a055e9d3b3770e.png"> are the same, <img alt="x_j - x_m \
eq 0" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/e/6/f/e6fd697895fa092c0bfe74e17cb248a3.png">, so this expression is always well-defined. The reason pairs <img alt="x_i = x_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/a/8/7/a87b533c7a1ed50d40fd0423b8a0ff0e.png"> with <img alt="y_i\
eq y_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/7/e/9/7e93c0f29ca466eba12e94297d3026c9.png"> are not allowed is that no interpolation function <img alt="L" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/d/2/0/d20caec3b48a1eef164cb4ca81ba2587.png"> such that <img alt="y_i = L(x_i)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/1/e/2/1e2facfa8374b5334ff2ce10434c8af9.png"> would exist; a function can only get one value for each argument <img alt="x_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/5/e/05e42209d67fe1eb15a055e9d3b3770e.png">. On the other hand, if also <img alt="y_i = y_j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/e/0/0/e001a24db77f5b3a9c9f6b97e69184f9.png">, then those two points would actually be one single point.

For all <img alt="i\
eq j" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/3/d/2/3d27367ea16a2a7b40b3eb3172a32120.png">, <img alt="\ell_j(x)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/3/7/c/37ca7ba34492aac83e9cda730482fd1f.png"> includes the term <img alt="(x-x_i)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/2/6/4/264d5b76c64d4ccee89a0341233c60f8.png"> in the numerator, so the whole product will be zero at <img alt="x=x_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/d/c/0/dc0ecd9fc7c5c0af9e242c81cdc9fe8c.png">:
</p><dl>
<dd><img alt="\ell_{j\
e i}(x_i) = \prod_{m\
eq j} \frac{x_i-x_m}{x_j-x_m} = \frac{(x_i-x_0)}{(x_j-x_0)} \cdots \frac{(x_i-x_i)}{(x_j-x_i)} \cdots \frac{(x_i-x_k)}{(x_j-x_k)} = 0." class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/6/9/0/690d4bf318254f2cd6df83f7465b66a0.png"></dd>
</dl><p>
On the other hand,
</p><dl>
<dd><img alt="\ell_i(x_i) := \prod_{m\
eq i} \frac{x_i-x_m}{x_i-x_m} = 1" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/f/6/b/f6b2783b9eb194c9e25a71b3810bd7e5.png"></dd>
</dl><p>
In other words, all basis polynomials are zero at <img alt="x=x_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/d/c/0/dc0ecd9fc7c5c0af9e242c81cdc9fe8c.png">, except <img alt="\ell_i(x)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/4/8/f/48f2b403ba559f606378d9aed42e1d14.png">, for which it holds that <img alt="\ell_i(x_i)=1" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/1/a/c/1acadce4b3593f74a51f8d13f4c53b13.png">, because it lacks the <img alt="(x-x_i)" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/2/6/4/264d5b76c64d4ccee89a0341233c60f8.png"> term.

It follows that <img alt="y_i \ell_i(x_i)=y_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/8/5/a/85a80eaa90627ea328db7aac97d359ed.png">, so at each point <img alt="x_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/0/5/e/05e42209d67fe1eb15a055e9d3b3770e.png">, <img alt="L(x_i)=y_i+0+0+\dots +0=y_i" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/1/7/c/17c9a71da2e856da48dc966689458a04.png">, showing that <img alt="L" class="mwe-math-fallback-image-inline tex" decoding="async" loading="lazy" src="https://upload.wikimedia.org/math/d/2/0/d20caec3b48a1eef164cb4ca81ba2587.png"> interpolates the function exactly. ( Definition Source : <a href="https://en.wikipedia.org/wiki/Lagrange_polynomial">Wikipedia</a> )

&nbsp;

The&nbsp;Lagrange Interpolation C Code is written below.
</p><pre class="lang:c decode:true" tabindex="0" title="Lagrange.c">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

double Lagrange(int n, int k,double value);
double* fx;
double* x;
double Calculate(int n, double x);
void main() {
	int size;
	double question;
	printf("Please enter function's point count:\
");
	scanf("%d", &size);

	fx = (double*)malloc(sizeof(double)*size);
	x = (double*)malloc(sizeof(double)*size);
	for (int i = 0; i &lt; size; i++)
	{
		printf("Enter  x(%d):", i);
		scanf("%lf", &x[i]);		
		printf("Enter fx(%d):", i);
		scanf("%lf", &fx[i]);
		printf("------\
");
	}
	printf("Please enter point to calculate:\
");
	scanf("%lf", &question);
	printf("\
");
	printf("Result =====&gt; f(%4.2lf) = %5.4lf\
",question, Calculate(size, question));
	printf("\
");
	system("PAUSE");
}

double Lagrange(int n, int k, double val)
{
	double result = 1;
	for (int i = 0; i &lt; n; i++)
	{
		if (i!=k)		
			result = result * (double)((val - x[i]) / (x[k] - x[i]));		
	}
	return result;
}

double Calculate(int n,double x)
{
	double intPolasyon = 0;
	double *L = (double*)malloc(sizeof(double)*n);
	double *F = (double*)malloc(sizeof(double)*n);
	for (int i = 0; i &lt; n; i++)
	{
		L[i] = Lagrange(n, i, x);		
		intPolasyon += fx[i] * L[i];
		printf("L(%d) = %5.3lf\
", i, L[i]);
	}
	
	printf("\
");
	return intPolasyon;
}</pre>
<figure class="wp-caption"><img alt="Lagrange Interpolation C Code Result" class="wp-image-161 size-full" decoding="async" height="779" loading="lazy" src="/wp-content/uploads/2016/03/output.png" title="Lagrange Interpolation C Code Result" width="535"><figcaption>Lagrange Interpolation C Code Result</figcaption></figure>]]></content:encoded></item>
<item><title>Arduino Timer Kullanımı Kesmeler - Interrupts</title><link>https://sinanbir.com/arduino-timer-kullanimi-kesmeler-avr-8-bit/</link><guid isPermaLink="true">https://sinanbir.com/arduino-timer-kullanimi-kesmeler-avr-8-bit/</guid><pubDate>Fri, 27 Nov 2015 03:19:47 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p class="st-72a68a"><strong>Arduino Timer Kullan&inodot;m&inodot; ve Ayarlanmas&inodot;</strong></p><p>
Merhaba arkada&scedil;lar, bu makalemde arduino ve ayn&inodot; zamanda avr 8 bit mimarisine sahip i&scedil;lemcilerde timer kullan&inodot;m&inodot;ndan bahsetmek istiyorum. Arduino ad&inodot; alt&inodot;nda toplanan nerdeyse t&uuml;m haz&inodot;r boardlarda kullan&inodot;lan i&scedil;lemciler atmega firmas&inodot;na ait olan avr-8 bit veya 32 bit i&scedil;lemcileridir. Bu i&scedil;lemcilerde timer kullanmaktan bahsetmeden &ouml;nce bu mimariye sahip t&uuml;m i&scedil;lemciler benzer &scedil;ekilde ayarlamalar yapabilece&gbreve;inizi belirtmek isterim. Her i&scedil;lemcide benim &ouml;rnek vererek anlataca&gbreve;&inodot;m timerlar bulunmayabilir.Bunun i&ccedil;in gerekli bilgiyi kulland&inodot;&gbreve;&inodot;n&inodot;z i&scedil;lemcinin datasheet dosyas&inodot;ndan &ouml;&gbreve;renebilirsiniz. ( Ornek : <a href="http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf" rel="noopener" target="_blank">Atmega328 </a>)

<strong>Timer Nedir ?</strong>


Timer belirli zaman aral&inodot;klar&inodot;nda yapmak istedi&gbreve;imiz olaylar&inodot;n ger&ccedil;ekle&scedil;mesinde&nbsp;bize yard&inodot;mc&inodot; olan yap&inodot;d&inodot;r. &Idot;&scedil;lemciye o zaman dilimi geldi&gbreve;inde ne yapmas&inodot; gerekti&gbreve;ini hat&inodot;rlat&inodot;r. Bu yap&inodot;lacak i&scedil;lem bir dizi kendi komutunuz&nbsp;yada timer&inodot;n destekledi&gbreve;i spesifik bir &ouml;zellik olabilir. &Ouml;rne&gbreve;in klasik bir &ouml;rnek olan belirli zaman aral&inodot;klar&inodot;nda herhangi bir &ccedil;&inodot;k&inodot;&scedil;a ba&gbreve;l&inodot; led'i yakmak istedi&gbreve;inizde timer kullanmad&inodot;&gbreve;&inodot;n&inodot;z&inodot; varsayarsak bu i&scedil;lemi ger&ccedil;ekle&scedil;tirmek i&ccedil;in ge&ccedil;en zaman&inodot; s&uuml;rekli olarak kontrol edebilir yada delay gibi ka&ccedil;&inodot;lmas&inodot; gereken komutlarla o an i&scedil;lemciyi bloke edebilirsiniz. Bunlar&inodot; yapmak yerine i&scedil;lemcide var olan&nbsp;bu yap&inodot;lar bize gereken zaman kontrol&uuml;n&uuml; sa&gbreve;lamaktad&inodot;rlar. Bunu yaparken i&scedil;lemcide di&gbreve;er paralel i&scedil;lemlerin devam etmesi ise bize &ccedil;oklu i&scedil;lem yapabilme yetene&gbreve;i kazand&inodot;r&inodot;yor.

&nbsp;

<strong>Timer Nas&inodot;l &Ccedil;al&inodot;&scedil;&inodot;r ?</strong>

Timerlar saya&ccedil; yazmac&inodot; olarak bilinen ( counter register ) de&gbreve;i&scedil;kenini periyodik olarak artt&inodot;r&inodot;rlar. Bu&nbsp;yazma&ccedil; belirli bir de&gbreve;ere kadar ula&scedil;abilir. Bu de&gbreve;eri belirleyen fakt&ouml;r ise kulland&inodot;&gbreve;&inodot;m&inodot;z timer'&inodot;n ka&ccedil; bit oldu&gbreve;udur. Genellikle 8 bit veya 16 bit olarak kar&scedil;&inodot;m&inodot;za &ccedil;&inodot;karlar. Bu yazma&ccedil; maksimum de&gbreve;erine ula&scedil;t&inodot;&gbreve;&inodot; zaman (8 bit ise bu de&gbreve;er 255 &ccedil;&uuml;nk&uuml; 0'dan ba&scedil;l&inodot;yor) &nbsp;s&inodot;f&inodot;ra resetlenir ve ta&scedil;man&inodot;n oldu&gbreve;una dair bir flag bit'i set edilir. Bu biti bizim takip etmemize gerek kalmadan Interrupt Service Routine (ISR) bu i&scedil;lemi bizim i&ccedil;in ger&ccedil;ekle&scedil;tirerek bizim kesme oldu&gbreve;undan haberdar olmam&inodot;z&inodot; sa&gbreve;lar. Bu flag bit'i i&ccedil;in gereken t&uuml;m kontrolleri ISR sa&gbreve;lamaktad&inodot;r. Peki timer counter de&gbreve;i&scedil;kenini periyodik olarak art&inodot;r&inodot;r dedik. Bu periyotu neye g&ouml;re referans al&inodot;p artt&inodot;r&inodot;r ? Timer &ccedil;al&inodot;&scedil;mas&inodot; i&ccedil;in bir clock sinyaline ihtiya&ccedil; duyar. Bu sinyal her olu&scedil;tu&gbreve;unda bu de&gbreve;i&scedil;keni bir artt&inodot;r&inodot;r. Bu sinyal harici olabilece&gbreve;i gibi dahili olarakta &ccedil;o&gbreve;u i&scedil;lemcide mevcuttur.

&Ouml;rne&gbreve;in siz bir timer'a 16MHz clock sinyali sa&gbreve;larsan&inodot;z, bu timer i&ccedil;in periyot :

T = 1 / f ( Frekans Hz olarak )

T= 1 / ( 16* 10^6 Hz )

T = 62.5 ns

E&gbreve;er 32Mhz olsayd&inodot; bu de&gbreve;er 31.25 ns olacakt&inodot;r. ( 1 sn = 10^9 ns)

&nbsp;

Yukar&inodot;da timerlar&inodot;n genel &ccedil;al&inodot;&scedil;ma mant&inodot;&gbreve;&inodot;ndan bahsettik. 8-bit AVR i&scedil;lemcilerinde birden &ccedil;ok timer mevcut. Her timer varsay&inodot;lan olarak arduino i&ccedil;in farkl&inodot; i&scedil;lemlerde kullan&inodot;lmak &uuml;zere ayarlanm&inodot;&scedil;t&inodot;r. Timerlar &uuml;zerinden bilmeyerek yapabilece&gbreve;imiz de&gbreve;i&scedil;iklerle zaman ba&gbreve;&inodot;ml&inodot; fonksiyonlarda beklenmedik sonu&ccedil;lar&nbsp;ile kar&scedil;&inodot;la&scedil;abiliriz. ( Motor, delay, millis vb.)

<strong>Varsay&inodot;lan Timer&nbsp;Ayarlar&inodot;</strong>
<strong>Timer0 -&nbsp;</strong>8-bit&nbsp;bir zamanlay&inodot;c&inodot;d&inodot;r. Counter de&gbreve;i&scedil;keni maksimum 255 de&gbreve;erini al&inodot;r. Arduino i&ccedil;in gerekli temel fonksiyonlar( delay() ve millis() gibi ) bu timer'a ba&gbreve;l&inodot;d&inodot;rlar. Bu timer &uuml;zerinde ne yapt&inodot;&gbreve;&inodot;n&inodot;z&inodot; bilmedi&gbreve;iniz s&uuml;rece de&gbreve;i&scedil;iklik yapmamak en iyisi olacakt&inodot;r.

<strong>Timer1 -&nbsp;</strong>16-bit bir zamanlay&inodot;c&inodot;d&inodot;r. Counter de&gbreve;i&scedil;keni maksimum 65535&nbsp;de&gbreve;erini al&inodot;r. Servo k&uuml;t&uuml;phanesi bu zamanlay&inodot;c&inodot;y&inodot; kullanmaktad&inodot;r.

<strong>Timer2 -&nbsp;</strong>8-bit&nbsp;bir zamanlay&inodot;c&inodot;d&inodot;r. Counter de&gbreve;i&scedil;keni maksimum 255 de&gbreve;erini al&inodot;r.<b>&nbsp;</b>tone() fonksiyonu&nbsp;bu zamanlay&inodot;c&inodot;y&inodot; kullanmaktad&inodot;r.

Kulland&inodot;&gbreve;&inodot;n&inodot;z i&scedil;lemcide bunlar&inodot;n d&inodot;&scedil;&inodot;nda farkl&inodot; Timer3, Timer4, Timer5 gibi zamanlay&inodot;c&inodot;lar bulunabilir. Gerekli bilgileri &ouml;nceden bahsetti&gbreve;im gibi onlar&inodot;n pdfleri &uuml;zerinden ula&scedil;abilirsiniz. Genel anlamda yapaca&gbreve;&inodot;m&inodot;z ayarlamalar&inodot;n hepsi birbiri i&ccedil;in ge&ccedil;erli olacakt&inodot;r.

<strong>Zamanlay&inodot;c&inodot; Yazma&ccedil;lar&inodot;n&inodot;n Ayarlanmas&inodot;</strong>

Timerlar i&ccedil;in gerekli ayarlar&inodot;n saklanaca&gbreve;&inodot; yazma&ccedil;lar vard&inodot;r. Bunlar &uuml;zerinde yukar&inodot;da bahsetti&gbreve;imiz ayarlamalar&inodot;n nas&inodot;l yap&inodot;laca&gbreve;&inodot;n&inodot; birazdan &ouml;rnekler &uuml;zerinde daha iyi anlayacaks&inodot;n&inodot;z. Bu yazma&ccedil;lardan iki tanesini timer ayarlar&inodot;n&inodot; set ederken kullan&inodot;r&inodot;z. Bunlar TCCRxA ve TCCRxB'dir. Herbir yazma&ccedil; 8 bit veri saklar.Burada x yerine ayarlamak istedi&gbreve;iniz timer rakam&inodot;n&inodot; yazabilirsiniz. A&scedil;a&gbreve;&inodot;da &ouml;rnek olarak Timer1 i&ccedil;in bu yazma&ccedil;lar&nbsp;verilmi&scedil;tir.


</p><div class="hfeed" id="page">
<div id="main">
<div id="primary">
<div id="content">
<a href="/wp-content/uploads/2015/11/tccr1a.png"><img class="alignnone wp-image-106 size-full" decoding="async" height="157" loading="lazy" src="/wp-content/uploads/2015/11/tccr1a.png" title="Timer 1 Register" width="854"></a>
<a href="/wp-content/uploads/2015/11/tccr1b.png"><img class="alignnone wp-image-107 size-full" decoding="async" height="154" loading="lazy" src="/wp-content/uploads/2015/11/tccr1b.png" title="Timer 1 Register B" width="855"></a>

Timer interrupt'&inodot;n&nbsp;periyotunu set ederken gerekli olan clock sinyalini 0 1 2 numaral&inodot; bitlerin kombinasyonlar&inodot;yla sa&gbreve;lar&inodot;z.

<a href="/wp-content/uploads/2015/11/clockselectBit1.png"><img class="alignnone wp-image-108 size-full" decoding="async" height="322" loading="lazy" src="/wp-content/uploads/2015/11/clockselectBit1.png" title="Interrupt set registers" width="861"></a>
</div>
</div>
</div>
</div><p>
&Ouml;rne&gbreve;in Timer1'i 2MHz clock h&inodot;z&inodot;nda &ccedil;al&inodot;&scedil;t&inodot;rmak istersek. Yani her count artt&inodot;r&inodot;m&inodot; i&ccedil;in ge&ccedil;en s&uuml;re 0.5us&nbsp;olacak bi&ccedil;imde ayarlarsak &nbsp;a&scedil;a&gbreve;&inodot;daki gibi bir kod blo&gbreve;u yazmam&inodot;z gerekir. Ben ornekleri arduino ide'si &uuml;zerinden anlat&inodot;yorum.
</p><pre class="lang:c decode:true" tabindex="0">#define PIN 13 // Board &uuml;zerinde var olan led. Arduino Uno R3

void setup()
{
  pinMode(PIN, OUTPUT);
  //  Timer1 Ayarlanmas&inodot;
  cli();         // t&uuml;m interruptlar dev d&inodot;&scedil;&inodot;
  TCCR1A = 0;    // t&uuml;m TCCR1A yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar
  TCCR1B = 0;    // t&uuml;m TCCR1B yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar

  // timer1 i&ccedil;in overflow interrupt&inodot;n&inodot; a&ccedil;ar
  TIMSK1 |= (1 &lt;&lt; TOIE1); //Kulland&inodot;&gbreve;&inodot;n&inodot;z i&scedil;lemcide bu timer yoksa farkl&inodot; bir timer ilede ayn&inodot; ayarlar&inodot; set edebilirsiniz

  // CS11 bitini atad&inodot;k vede timer &scedil;uanda clock h&inodot;z&inodot;nda &ccedil;al&inodot;&scedil;acakt&inodot;r.
  TCCR1B |= (1 &lt;&lt; CS11); //  b&ouml;leni 8 olarak ayarlad&inodot;k. Yani 16/8 = 2 MHZ

  sei();//T&uuml;m interruptlar&inodot; &ccedil;al&inodot;&scedil;t&inodot;r.

}

void loop()
{

}</pre>
<p><strong>Overflow&nbsp;Interrupt</strong>

Burada yapt&inodot;&gbreve;&inodot;m&inodot;z ayarlamada timer'&inodot;n ne t&uuml;r bir kesme kullanaca&gbreve;&inodot;n&inodot; belirtmedik. Bunun kontrol&uuml;n&uuml;&nbsp;sa&gbreve;layan&nbsp;Timer/Counter1 Interrupt Mask Register TIMSK1'dir. Bu yazmaca TOIE1 atamas&inodot; yaparak timer'in ta&scedil;ma (overflow ) interrupt&inodot; kullanmas&inodot;n&inodot; set ederiz. Biraz daha sonra farkl&inodot; bir kesme t&uuml;r&uuml; olan CTC ( Clear Timer on Compare Match ) kesmesinden de bahsedece&gbreve;im. &Scedil;imdi kald&inodot;&gbreve;&inodot;m&inodot;z yerden devam edecek olursak overflow olu&scedil;tu&gbreve;u zaman ISR(TIMER1_OVF_vect) &ccedil;a&gbreve;r&inodot;l&inodot;r.Sonu&ccedil; olarak :
</p><pre class="lang:c decode:true" tabindex="0">#define PIN 13 // Board &uuml;zerinde var olan led. Arduino Uno R3

void setup()
{
  pinMode(PIN, OUTPUT);
  //  Timer1 Ayarlanmas&inodot;
  cli();         // t&uuml;m interruptlar dev d&inodot;&scedil;&inodot;
  TCCR1A = 0;    // t&uuml;m TCCR1A yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar
  TCCR1B = 0;    // t&uuml;m TCCR1B yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar

  // timer1 i&ccedil;in overflow interrupt&inodot;n&inodot; a&ccedil;ar
  TIMSK1 |= (1 &lt;&lt; TOIE1); //Kulland&inodot;&gbreve;&inodot;n&inodot;z i&scedil;lemcide bu timer yoksa farkl&inodot; bir timer ilede ayn&inodot; ayarlar&inodot; set edebilirsiniz

  // CS11 bitini atad&inodot;k vede timer &scedil;uanda clock h&inodot;z&inodot;nda &ccedil;al&inodot;&scedil;acakt&inodot;r.
  TCCR1B |= (1 &lt;&lt; CS11); //  b&ouml;leni 8 olarak ayarlad&inodot;k. Yani 16/8 = 2 MHZ
  TIMSK1 | = (1 &lt;&lt; TOIE1); // Overflow kesmesini a&ccedil;ar&inodot;z
  sei();//T&uuml;m interruptlar&inodot; &ccedil;al&inodot;&scedil;t&inodot;r.

}

void loop()
{

}
ISR(TIMER1_OVF_vect)
{

  digitalWrite(PIN, !digitalRead(PIN));

}</pre><p>
Buraya kadar olan b&ouml;l&uuml;mde kesme tan&inodot;mlamas&inodot;n&inodot; olu&scedil;turduk. Kesme frekans&inodot;n&inodot; hepsaplayacak olursak:
</p><ul>
<li>Clock sinyalimizi 8 b&ouml;leni kullanarak ( CS11 ) set ettik yani 2MHz clock sinyali elde ettik</li>
<li>Bir count de&gbreve;eri artt&inodot;rmak i&ccedil;in ge&ccedil;en s&uuml;re 0.5us.</li>
<li>Counter de&gbreve;eri 0 - 65535'e &ccedil;&inodot;karken 65536 de&gbreve;er artt&inodot;rm&inodot;&scedil; olur.</li>
<li>T = 65536*0.5 =32.77ms&nbsp;olur</li>
<li>f=1/T =&nbsp;30.51 Hz</li>
</ul><p>
Yani bizim ISR fonksiyonumuz saniyede yakla&scedil;&inodot;k olarak 30.51&nbsp;kere &ccedil;al&inodot;&scedil;t&inodot;r&inodot;lacak.

&nbsp;

Overflow kesmesinin baz&inodot; dezavantajlar&inodot;ndan birtanesi istedi&gbreve;imiz frekans de&gbreve;erlerinin tam olarak ayarlanabilmesinin zor olmas&inodot;. &Ccedil;&uuml;nk&uuml; her seferinde counter'&inodot;n sona kadar artt&inodot;r&inodot;l&inodot;p kesmenin olu&scedil;mas&inodot; beklenmekte. Bunun yerine daha hassas frekans oynamalar&inodot; yapabilmek i&ccedil;in timer'in bizim belirledi&gbreve;imiz bir&nbsp;de&gbreve;ere ula&scedil;mas&inodot;ndan sonra kesme olu&scedil;mas&inodot;n&inodot; sa&gbreve;layabilece&gbreve;imiz mod olan CTC modundan bahsetmek istiyorum.

&nbsp;

<strong>Clear Timer on Compare Match Kesmesi ( CTC )</strong>

Timer'&inodot;n counter de&gbreve;erinin overflow yapmas&inodot;n&inodot; beklemek yerine, bizim daha &ouml;nceden set etti&gbreve;imiz bir count de&gbreve;erine e&scedil;it olunca olu&scedil;an bir kesmedir.

Burada bu de&gbreve;eri atayabilece&gbreve;imiz register&nbsp;ACRxA'd&inodot;r. Burada x se&ccedil;ece&gbreve;imiz timer'a g&ouml;re farkl&inodot;l&inodot;k g&ouml;stermektedir. Ayn&inodot; zamanda atayaca&gbreve;&inodot;m&inodot;z maksimum de&gbreve;er bu se&ccedil;ti&gbreve;imiz timer'&inodot;n ka&ccedil; bit oldu&gbreve;una g&ouml;re de&gbreve;i&scedil;ir. Yine &ouml;rnek olarak timer1 kullancak olursak atayaca&gbreve;&inodot;m&inodot;z de&gbreve;erler i&scedil;aretsiz 65536'dan k&uuml;&ccedil;&uuml;k de&gbreve;erler olmal&inodot;d&inodot;r. Timer0 kullancak olursak bu de&gbreve;er 256'dan k&uuml;&ccedil;&uuml;kt&uuml;r. Bu modu kullanman&inodot;n di&gbreve;er bir avantaj&inodot; timer0 kullan&inodot;rken default prescale (64 b&ouml;leni) kullan&inodot;rsak overflow kesmesinde herhangi bir de&gbreve;i&scedil;iklik olmad&inodot;&gbreve;&inodot; i&ccedil;in di&gbreve;er temel fonksiyolar do&gbreve;ru &ccedil;al&inodot;&scedil;maya devam edecektir. Yani timer0'&inodot;da bu mod ile kesmelerde kullanabiliriz. Fakat 8 bit olmas&inodot;ndan dolay&inodot; uyarlayabilece&gbreve;imiz frekans aral&inodot;klar&inodot; s&inodot;n&inodot;rl&inodot; olacakt&inodot;r. Burada size istedi&gbreve;iniz frekans&inodot; elde edebileci&gbreve;iniz bir formul vermek istiyorum. Bu formul ile istedi&gbreve;iniz frekansa ula&scedil;mak i&ccedil;in gereken ad&inodot;m say&inodot;s&inodot;n&inodot; kolayca hesaplayabilirsiniz.

<a href="/wp-content/uploads/2015/11/comparematchregister.png"><img alt="Interrupts" class="alignnone wp-image-116 size-full" decoding="async" height="95" loading="lazy" src="/wp-content/uploads/2015/11/comparematchregister.png" title="Compare Value" width="471"></a>

Formulde yer alan frekans de&gbreve;eri elde etmek istedi&gbreve;imiz frekanst&inodot;r. B&ouml;len daha &ouml;nce bahsetti&gbreve;imiz i&scedil;lecinin clock h&inodot;z&inodot;n&inodot; ayarlad&inodot;&gbreve;&inodot;m&inodot;z de&gbreve;erdir. 1 &ccedil;&inodot;karmam&inodot;z&inodot;n nedeni 0'dan ba&scedil;l&inodot;yor olmas&inodot;d&inodot;r. &Scedil;imdi bir &ouml;rnek ile 16KHz kesme frekans&inodot; olu&scedil;tural&inodot;m.
</p><pre class="lang:autoit decode:true" tabindex="0">#define PIN 13 // Board &uuml;zerinde var olan led. Arduino Uno R3

void setup()
{
  pinMode(PIN, OUTPUT);
  //  Timer1 Ayarlanmas&inodot;
  cli();         // t&uuml;m interruptlar dev d&inodot;&scedil;&inodot;
  TCCR1A = 0;    // t&uuml;m TCCR1A yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar
  TCCR1B = 0;    // t&uuml;m TCCR1B yazmac&inodot;n&inodot; s&inodot;f&inodot;rlar

  TCCR1A |= (1 &lt;&lt; WGM21); // CTC modunu aktif hale getirir
  // CS11 bitini atad&inodot;k vede timer &scedil;uanda clock h&inodot;z&inodot;nda &ccedil;al&inodot;&scedil;acakt&inodot;r.
  OCR2A = 124;// ((16*10^6)/(16000*8))-1 Bize 16KHz kesme frekans&inodot; sa&gbreve;lar
  TCCR1B |= (1 &lt;&lt; CS11); //  b&ouml;leni 8 olarak ayarlad&inodot;k. Yani 16/8 = 2 MHZ clock sinyali
  TIMSK1 |= ( 1 &lt;&lt; OCIE1A); // Timer Compare kesmesini aktif hale getir.
  sei();//T&uuml;m interruptlar&inodot; &ccedil;al&inodot;&scedil;t&inodot;r.

}

void loop()
{

}
ISR(TIMER1_COMPA_vect) // 16 KHz frekansa sahip.
{

  digitalWrite(PIN, !digitalRead(PIN)); // A&ccedil; kapa 2 kesme tuttu&gbreve;u i&ccedil;in &ccedil;&inodot;k&inodot;&scedil;ta &ouml;l&ccedil;ece&gbreve;iniz de&gbreve;er 8KHz olacakt&inodot;r.

}</pre><p>
&nbsp;

Kesmeler ile de&gbreve;i&scedil;kenleri kullan&inodot;rken dikkat edilmesi gereken &ouml;nemli bir nokta ise <strong>volatile</strong> de&gbreve;imidir. Bu tan&inodot;mlama ile de&gbreve;i&scedil;kenlerde farkl&inodot; kesmelerinin de&gbreve;i&scedil;ken &uuml;zerinde s&inodot;ral&inodot; i&scedil;lem yapmas&inodot;n&inodot; sa&gbreve;lay&inodot;p daha stabil g&uuml;venilir bir saklama yapm&inodot;&scedil; oluruz. &Ccedil;ok y&uuml;ksek frekans de&gbreve;erlerinde bu deyim yeterli olmay&inodot;p kesmeyi devre d&inodot;&scedil;&inodot; b&inodot;rak&inodot;p de&gbreve;i&scedil;keni okuyup tekrar a&ccedil;ma i&scedil;lemide uygulanabilir. Ba&scedil;ka bir makalede g&ouml;r&uuml;&scedil;mek &uuml;zere ho&scedil;cakal&inodot;n.

&nbsp;

&nbsp;

&nbsp;</p>]]></content:encoded></item>
<item><title>Web Api Bearer Token  Authentication</title><link>https://sinanbir.com/web-api-bearer-token-authentication/</link><guid isPermaLink="true">https://sinanbir.com/web-api-bearer-token-authentication/</guid><pubDate>Wed, 14 Oct 2015 17:39:28 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>Bu makalemde front-end ve back-end aras&inodot;nda web api bearer token &nbsp;authentication&nbsp;kullan&inodot;m&inodot;ndan&nbsp;bahsetmek istiyorum.&nbsp;&Idot;lk olarak nedir bu token diyerek ba&scedil;lay&inodot;p&nbsp;avantajlar&inodot;ndan bahsettikten sonra &ouml;rnek bir ASP .NET Web Api &Uuml;zerinden uygulama ile devam edece&gbreve;im.

&nbsp;

<strong>Nedir Bu Token ve Avantajlar&inodot; ?</strong>

K&inodot;saca &ouml;zetlemek gerekirse token'&inodot; anahtar olarak d&uuml;&scedil;&uuml;nebiliriz. Yani biz back-end server&inodot;m&inodot;za kullan&inodot;c&inodot; ad&inodot;m&inodot;z&inodot; ve &scedil;ifremizi do&gbreve;rulamak i&ccedil;in g&ouml;nderdi&gbreve;imizde bize bu do&gbreve;rulamaya kar&scedil;&inodot;l&inodot;k&nbsp;bir token ( Anahtar ) veriyor. Sonras&inodot;nda istek ger&ccedil;ekle&scedil;tirmek istedi&gbreve;imizde bizden kullan&inodot;c&inodot; ad&inodot; &scedil;ifre yerine bu anahtar&inodot; bekliyor ve gerekli g&uuml;venlik kontrollerini sa&gbreve;l&inodot;yor. Burada b&ouml;yle bir yap&inodot;n&inodot;n kullan&inodot;lmas&inodot;n&inodot;n bize sa&gbreve;lad&inodot;&gbreve;&inodot; avantajlardan ba&scedil;l&inodot;calar&inodot;;


</p><ul>
<li>Mobil uygulamalar ile entegrasyonu</li>
<li>Farkl&inodot; uygulamalar ile do&gbreve;rulaman&inodot;n payla&scedil;&inodot;labilmesi</li>
<li>Durumsuz olmas&inodot; &nbsp;(&nbsp;Stateless ) ve sonucunda daha kolay &ouml;l&ccedil;eklenebilir olmas&inodot;</li>
<li>Front-end ile back-end aras&inodot;nda gev&scedil;ek (loosely coupled) bir yap&inodot; sa&gbreve;lamas&inodot;</li>
</ul>
<p><strong>Uygulama &Idot;le Devam Edelim...</strong>

&Ouml;rnek uygulamam&inodot;z&inodot; olu&scedil;tururken iki tane projeye ihtiyac&inodot;m&inodot;z olacak. Bir tanesi bo&scedil; web-api projemiz ikincisi ise bo&scedil; bir web projesi olacak.
</p><h2>Web Api Bearer Token &nbsp;Authentication Projesi</h2><p>
Bo&scedil; web-api projemizi "OrnekWebApi" &scedil;eklinde adland&inodot;r&inodot;p ba&scedil;layal&inodot;m.Projemize kullanaca&gbreve;&inodot;m&inodot;z paket eklentilerini y&uuml;kleyelim. Bunlar i&ccedil;in;
</p><blockquote><span class="crayon-r">Install-Package</span> Microsoft<span class="crayon-sy">.</span>AspNet<span class="crayon-sy">.</span>WebApi<span class="crayon-sy">.</span>Owin

Install-Package Microsoft.Owin.Security.OAuth

<span class="crayon-r">Install-Package</span> Microsoft<span class="crayon-sy">.</span>Owin<span class="crayon-sy">.</span>Cors

<span class="crayon-r">Install-Package</span> Microsoft<span class="crayon-sy">.</span>Owin<span class="crayon-sy">.</span>Host<span class="crayon-sy">.</span>SystemWeb</blockquote><p>
Paket y&uuml;klemelerini ger&ccedil;ekle&scedil;tirdikten sonra a&scedil;a&gbreve;&inodot;da &scedil;ekilde g&ouml;r&uuml;ld&uuml;&gbreve;&uuml; gibi bir klas&ouml;r yap&inodot;s&inodot; olu&scedil;turup i&ccedil;erine "Saglayici" ve "Startup" klas&inodot;m&inodot;z&inodot; ekleyelim.

<a href="/wp-content/uploads/2015/10/projeyapi.png"><img alt="projeyapi" class="alignnone size-full wp-image-76" decoding="async" height="262" loading="lazy" src="/wp-content/uploads/2015/10/projeyapi.png" width="340"></a>

Startup klas&inodot;m&inodot;z i&ccedil;ine a&scedil;a&gbreve;&inodot;daki kodlar&inodot; yap&inodot;&scedil;t&inodot;ral&inodot;m.
</p><pre class="lang:c# decode:true" tabindex="0" title="Startup.cs">using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;


[assembly: OwinStartup(typeof(OrnekWebApi.Authentication.Startup))]
namespace OrnekWebApi.Authentication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);            
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new Microsoft.Owin.PathString("/token"), // token adresi
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(10),//10 Saat ge&ccedil;erli
                AllowInsecureHttp = true,
                Provider = new Saglayici() // Burada hata al&inodot;rsan&inodot;zz saglay&inodot;c&inodot; klas&inodot;n&inodot;z&inodot;z do&gbreve;ru ayarlad&inodot;&gbreve;&inodot;n&inodot;zdan emin olun.
            };

            
            app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions); // Ayarlad&inodot;&gbreve;&inodot;m&inodot;z config dosyas&inodot;n&inodot;n server'a kullanmas&inodot; i&ccedil;in g&ouml;nderiyoruz.
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());// Bearer Authentication'&inodot; kullanaca&gbreve;&inodot;m&inodot;z&inodot; belirttik.
        }
    }
}</pre><p>
&nbsp;

Burada yukar&inodot;da tan&inodot;mlad&inodot;&gbreve;&inodot;m&inodot;z assembly ile server&inodot;m&inodot;z ilk &ccedil;al&inodot;&scedil;t&inodot;&gbreve;&inodot;nda &ccedil;al&inodot;&scedil;t&inodot;r&inodot;lacak klas&inodot;m&inodot;z&inodot; tan&inodot;mlad&inodot;k. &nbsp;Configuration k&inodot;sm&inodot;nda yer alan parametre ise bu &ccedil;a&gbreve;r&inodot;lma s&inodot;ras&inodot;nda host taraf&inodot;ndan sa&gbreve;lanmakta. &Idot;kinci olarak&nbsp;HttpConfiguration ayarlar&inodot;m&inodot;z&inodot; yapt&inodot;ktan sonra App_Start'da yer alan Register metodumuzu bu configrasyon ile &ccedil;a&gbreve;&inodot;raca&gbreve;&inodot;z.Bu i&scedil;lemin ard&inodot;ndan projemizde yer alan Global.asax.cs dosyam&inodot;z&inodot;n bulunmas&inodot;na gerek kalmamaktad&inodot;r. &Ccedil;&uuml;nk&uuml; startup i&scedil;lemini art&inodot;k buradan sa&gbreve;l&inodot;yoruz. OAuth server ayarlar&inodot;nda tan&inodot;mlad&inodot;&gbreve;&inodot;m&inodot;z &ouml;zelliklerden bahsedecek olursak
</p><blockquote>TokenEndpointPath ile ge&ccedil;erli token alaca&gbreve;&inodot;m&inodot;z adresi belirtiyoruz.

AccessTokenExpireTimeSpan ise sa&gbreve;lanan token'&inodot;n ge&ccedil;erlilik s&uuml;resini belirtir.

AllowInsecureHttp ise token&nbsp;requestlerin HTTPS olmayan protokollere a&ccedil;&inodot;lmas&inodot;n&inodot; sa&gbreve;lar.</blockquote><p>
&Scedil;imdi ikinci klas&inodot;m&inodot;z olan sa&gbreve;lay&inodot;c&inodot; klas&inodot;m&inodot;z i&ccedil;in kodlar&inodot; payla&scedil;al&inodot;m.
</p><pre class="lang:c# decode:true" tabindex="0" title="Saglayici.cs">using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
namespace OrnekWebApi.Authentication
{
    public class Saglayici : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
//Burada client validation kullanmad&inodot;k. &Idot;stersek custom client tipleri ile client tipine g&ouml;rede validation sa&gbreve;layabiliriz.
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); // Farkl&inodot; domainlerden istek sorunu ya&scedil;amamak i&ccedil;in

            //Burada kendi authentication y&ouml;ntemimizi belirleyebiliriz.Veritaban&inodot; ba&gbreve;lant&inodot;s&inodot; vs...
            if (context.UserName == "Sinan" && context.Password == "Bir")
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim("name", context.UserName));
                identity.AddClaim(new Claim("yetki", "Admin"));

                context.Validated(identity);
            }
            else
            {
                context.SetError("Ge&ccedil;ersiz istek", "Hatal&inodot; kullan&inodot;c&inodot; bilgisi");
            }

            

        }
    }
}</pre><p>
&nbsp;

&Scedil;imdi son olarak Authentication'&inodot; test edebilece&gbreve;imiz bir controller olu&scedil;turup projenin web-api k&inodot;sm&inodot;n&inodot; tamamlamak."Fatura" isminde bo&scedil; bir web-api 2 controller olu&scedil;tural&inodot;m.
</p><pre class="lang:c# decode:true" tabindex="0">using System.Collections.Generic;
using System.Web.Http;


namespace OrnekWebApi.Controllers
{
    public class FaturaController : ApiController
    {
        [HttpGet]
        [Authorize]
        public IEnumerable&lt;string&gt; Get()
        {
            var firmaList = new List&lt;string&gt;()
            {
                "Firma 1",
                "Firma 2",
                "Firma 3",
            };
            return firmaList;
        }   
    }
}
</pre><p>
Burada [Authorize]&nbsp;attribute'i ile get metodumuzun yetkilendirme gerektirece&gbreve;ini belirttik. Buraya kadarki b&ouml;l&uuml;mde web-api projemizi tamamlad&inodot;k. &Scedil;imdi projemizi&nbsp;test etmek i&ccedil;in bo&scedil; bir web projesi a&ccedil;&inodot;p yap&inodot;land&inodot;rmalara devam edelim.

&nbsp;

<strong>Web Projemiz</strong>

Bo&scedil; bir web-mvc projesi a&ccedil;al&inodot;m. Projemize birtek jquery y&uuml;klememiz yeterli. &nbsp;Ard&inodot;ndan a&scedil;a&gbreve;&inodot;da verece&gbreve;im java script kodunu ekleyin.
</p><pre class="lang:js decode:true" tabindex="0" title="App.js">$(document).ready(function() {
    $("#Login").click(function() {
        var userName = $("#UserName").val();
        var password = $("#Password").val();
        
        $.ajax({
            url: "http://localhost:11050/token",
            type: "POST",
            crossDomain: true,
            data: {
                "username": userName,
                "password": password,
                "grant_type": "password"
            },
            dataType: "json",
            success: function (result) {
                alert("Logged in successfully");
                localStorage.setItem('Token', JSON.stringify(result));
            },
            error: function (xhr, status, error) {
                alert(status+" " +error);
            }
        });
        
    });
    $("#Logout").click(function () {
        if (localStorage.getItem('Token')==null) {
            alert("You already logged out");
            return;
        }
        alert("Logged out successfully");
        localStorage.removeItem('Token');
    });
    $("#Get").click(function () {
        var token = $.parseJSON(localStorage.getItem('Token'));
        if (token == null) {
            alert("Unauthorized Request");
            return;
        }
        var accessToken = token.access_token;
        
       
        $.ajax({
            url: "http://localhost:11050/api/Fatura",
            type: "Get",
            crossDomain: true,
            dataType: "json",
            headers: {
                "accept": "application/json",
                "content-type": "application/json",
                "authorization": "Bearer "+ accessToken
                },
            success: function (result) {
                alert(JSON.stringify(result));
            },
            error: function (xhr, status, error) {
                alert(status + " " + error);
            }
        });
    });
});</pre><p>
&nbsp;

Burada serverdan d&ouml;nen token'&inodot; local storage kaydettim. Siz farkl&inodot; bir yap&inodot;da kullanabilirsiniz. Index sayfas&inodot; i&ccedil;in kodlar&inodot; payla&scedil;&inodot;yorum.
</p><pre class="lang:xhtml decode:true" tabindex="0">&lt;!DOCTYPE html&gt;

&lt;html&gt;
&lt;head&gt;
    &lt;meta name="viewport" content="width=device-width"/&gt;
    &lt;script src="~/Scripts/jquery-2.1.4.min.js"&gt;&lt;/script&gt;
    &lt;script src="~/App/App.js"&gt;&lt;/script&gt;
    &lt;title&gt;Index&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;input id="UserName" type="text" value="Sinan"/&gt;
&lt;input id="Password" type="password" value="Bir"/&gt;
&lt;input id="Login" type="button" value="Login"/&gt;
&lt;input id="Logout" type="button" value="Logout" /&gt;
&lt;input id="Get" type="button" value="Get Data" /&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre><p>
&nbsp;

&nbsp;

Giri&scedil; yapt&inodot;&gbreve;&inodot;n&inodot;zda sonu&ccedil; a&scedil;a&gbreve;&inodot;daki gibi olacakt&inodot;r.

<a href="/wp-content/uploads/2015/10/logginsuccess.png"><img alt="Web Api Bearer Token Authentication" class="alignnone wp-image-80 size-full" decoding="async" height="561" loading="lazy" src="/wp-content/uploads/2015/10/logginsuccess.png" title="Web Api Bearer Token Authentication" width="1539"></a>

Veri iste&gbreve;i yapt&inodot;&gbreve;&inodot;m&inodot;zdaki sonu&ccedil;

<a href="/wp-content/uploads/2015/10/getdata.png"><img alt="getdata" class="alignnone size-full wp-image-81" decoding="async" height="307" loading="lazy" src="/wp-content/uploads/2015/10/getdata.png" width="938"></a>
<a href="https://github.com/deluxetiky/WebApiTokenBasedExample">Proje</a> dosyalar&inodot; github'da mevcuttur.

&nbsp;</p>]]></content:encoded></item>
<item><title>.Net - NLog Kullanımı ( Error - System Logging )</title><link>https://sinanbir.com/net-nlog-kullanimi-error-logging/</link><guid isPermaLink="true">https://sinanbir.com/net-nlog-kullanimi-error-logging/</guid><pubDate>Mon, 28 Sep 2015 19:12:25 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>Merhaba arkada&scedil;lar,uygulama geli&scedil;tirirken hata y&ouml;netimi konusunun &ouml;nemi bir hayli fazla. Kullan&inodot;c&inodot;n&inodot;n kar&scedil;&inodot;la&scedil;t&inodot;&gbreve;&inodot; hatalar&inodot;n saklanmas&inodot; bize bu hatalar&inodot;n &ccedil;&ouml;z&uuml;m&uuml;nde b&uuml;y&uuml;k bir kolayl&inodot;k sa&gbreve;layacakt&inodot;r. Ben projelerimde kulland&inodot;&gbreve;&inodot;m bir framework olan NLog'tan bahsetmek istiyorum.Bu arada free olmas&inodot; da bir hayli cezbedici. Ayr&inodot;ca kullan&inodot;&scedil;l&inodot; ve kurulumu da bir o kadar kolay. NLog ile bir hata&nbsp;olu&scedil;tu&gbreve;u durumda yapabileceklerinizden bahsetmek gerekirse;&nbsp;mail atabilirsiniz,dosyaya yazabilirsiniz, veritaban&inodot;na ekleyebilirsiniz&nbsp;, console'a &ccedil;&inodot;kt&inodot; alabilirsiniz ve daha bir &ccedil;ok sa&gbreve;lay&inodot;c&inodot; ile kullanabilirsiniz. Ben bu makalemde dosyaya saklama i&scedil;leminden&nbsp;bahsetmek istiyorum. &Ouml;rnek uygulama i&ccedil;in bir konsol&nbsp;projesi olu&scedil;turup bu projede genel hata y&ouml;netimi entegrasyonunu&nbsp;yapaca&gbreve;&inodot;z. &Scedil;imdi bir &ouml;rnek ile ba&scedil;layal&inodot;m...

Bo&scedil; bir proje olu&scedil;tural&inodot;m.



Nuget paket y&ouml;neticisine
</p><blockquote>Install-Package NLog</blockquote><p>
yazarak eklentiyi y&uuml;kleyelim.

Daha sonra proje klasor&uuml;ne nlog i&ccedil;in gerekli olan NLog.config dosyas&inodot;n&inodot; ekleyelim ve i&ccedil;ine a&scedil;a&gbreve;&inodot;daki kodlar&inodot; yap&inodot;&scedil;t&inodot;ral&inodot;m.
</p><pre class="theme:classic lang:xhtml decode:true" tabindex="0" title="NLog.config">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true" &gt;

  &lt;variable name="logDirectory"  value="${basedir}/logs/${shortdate}" /&gt;
  &lt;targets async="true"&gt; 
    
      &lt;target name="FileManager"
              xsi:type="File"
              layout="${longdate} ${threadid:padding=4} ${level:uppercase=true:padding=5} ${logger} ${message} ${exception:format=tostring}"
              fileName="${logDirectory}/log.txt"
              archiveFileName="${logDirectory}/log.{#}.txt"
              archiveEvery="Day"
              archiveNumbering="Rolling"
              maxArchiveFiles="7"
              concurrentWrites="true"
              createDirs="true"
              autoFlush="true" /&gt;
     &lt;target name="FileManager2"
              xsi:type="File"
              layout="${longdate} ${threadid:padding=4} ${level:uppercase=true:padding=5} ${logger} ${message} ${exception:format=tostring}"
              fileName="${logDirectory}/log2.txt"
              archiveFileName="${logDirectory}/log.{#}.txt"
              archiveEvery="Day"
              archiveNumbering="Rolling"
              maxArchiveFiles="7"
              concurrentWrites="true"
              createDirs="true"
              autoFlush="true" /&gt;

     
  &lt;/targets&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Trace" maxlevel="Warn" writeTo="FileManager" /&gt;
  &lt;logger name="*" minlevel="Error" writeTo="FileManager2" /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;</pre><p>
Burada config dosyas&inodot;nda de&gbreve;inmek istedi&gbreve;im baz&inodot; noktalar var. Rules b&ouml;l&uuml;m&uuml;nde kurallar olu&scedil;turabiliyoruz. Bu kurallar i&ccedil;erisinde "minlevel" loglama i&scedil;leminin hangi seviyeden sonra ger&ccedil;ekle&scedil;ece&gbreve;ini tan&inodot;ml&inodot;yor.Ayn&inodot; &scedil;ekilde "maxlevel" &ouml;zelli&gbreve;inide tan&inodot;mlayabiliriz. Bu seviyeler a&scedil;a&gbreve;&inodot;daki gibi :
</p><table>
<thead>
<tr>
<th>Seviye</th>
<th>A&ccedil;&inodot;klama</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fatal</td>
<td>&Uuml;st Seviye : Sistem &ccedil;&ouml;kmeleri</td>
</tr>
<tr>
<td>Error</td>
<td>Uygulama hatalar&inodot; ( Exceptions )</td>
</tr>
<tr>
<td>Warn</td>
<td>Uyar&inodot;lar, yinede uygulama &ccedil;al&inodot;&scedil;maya devam edebilir.</td>
</tr>
<tr>
<td>Info</td>
<td>Bilgilendirme herhangi bir ama&ccedil;l&inodot; olabilir. Kullan&inodot;c&inodot; bilgileri g&uuml;ncellendi vs.</td>
</tr>
<tr>
<td>Debug</td>
<td>&Ccedil;al&inodot;&scedil;t&inodot;r&inodot;lan sorgular, oturum s&uuml;resinin bitmesi vs.</td>
</tr>
<tr>
<td>Trace</td>
<td>Bir eylem ba&scedil;lad&inodot; di&gbreve;eri bitti gibi. &Ouml;rn : Fonksiyon&nbsp;ba&scedil;lang&inodot;c&inodot; ve biti&scedil;i durumlar&inodot;( En Alt Seviye )</td>
</tr>
</tbody>
</table><p>
&nbsp;

&Idot;kinci bir &ouml;nemli &ouml;zellik ise "writeTo". Bununla loglama kural&inodot; i&ccedil;in hangi target sistemini kullanaca&gbreve;&inodot;n&inodot; belirtiyoruz. Biz target olarak dosyalamaya uygun ayarlar&inodot;&nbsp;kullanaca&gbreve;&inodot;z.Bu ayarlar&inodot; yapt&inodot;ktan sonra config dosyas&inodot;ndaki tan&inodot;mlamada&nbsp;throwExceptions="true" olmas&inodot; olas&inodot; config&nbsp;hatalar&inodot;n&inodot; g&ouml;rmemizde bize yard&inodot;mc&inodot; olacakt&inodot;r. Program biti&scedil;inde bunun false yap&inodot;lmas&inodot;nda fayda var.&Ccedil;&uuml;nk&uuml; uygulama &ccedil;al&inodot;&scedil;&inodot;rken hata yada bilgilendirme i&ccedil;in kulland&inodot;&gbreve;&inodot;m&inodot;z eklentinin de hata vermesini istemeyiz. &Scedil;imdi &ouml;rnek bir program ile &ccedil;&inodot;kt&inodot;lar&inodot; kontrol edelim.
</p><pre class="lang:c# decode:true" tabindex="0">static void Main(string[] args)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();
            // Trace - Warn levellar&inodot; aras&inodot;nda FileManager2'yi kullanacak.
            logger.Log(LogLevel.Info, "Sample Info error message");
            logger.Log(LogLevel.Debug, "Sample Debug");
            logger.Log(LogLevel.Warn, "Sample Warn");
            logger.Log(LogLevel.Trace, "Sample Trace");
            //Error ve yukar&inodot;s&inodot; i&ccedil;in FileManager'&inodot; kullanacak.
            logger.Log(LogLevel.Error, new Exception("Hata1"));
            logger.Log(LogLevel.Error, new Exception("Hata2"));
            
        }</pre><p>
Program&inodot; &ccedil;al&inodot;&scedil;t&inodot;rd&inodot;ktan sonra. Dosyalar&inodot; kontrol etti&gbreve;imizde &ccedil;&inodot;kt&inodot; a&scedil;a&gbreve;&inodot;daki gibi olacakt&inodot;r.

<a href="/wp-content/uploads/2015/09/logresult.png"><img alt="logresult" class="alignnone size-full wp-image-62" decoding="async" height="271" loading="lazy" src="/wp-content/uploads/2015/09/logresult.png" width="1464"></a>

&nbsp;

G&ouml;rd&uuml;&gbreve;&uuml;n&uuml;z gibi farkl&inodot; seviye hatalar i&ccedil;in farl&inodot; dosyalar tuttuk. Burada biz target olarak dosya se&ccedil;tik e&gbreve;er mail se&ccedil;mi&scedil; olsayd&inodot;k ayn&inodot; &ccedil;&inodot;kt&inodot;lar&inodot; mail olarak alabilirdik. Detayl&inodot; target configrasyonlar&inodot;n&inodot; framework sitesinde bulabilirsiniz. Ba&scedil;ka bir makalede g&ouml;r&uuml;&scedil;mek &uuml;zere. Ho&scedil;&ccedil;akal&inodot;n.

&nbsp;

&nbsp;</p>]]></content:encoded></item>
<item><title>Web Api Simple Injector Dependcy Resolver</title><link>https://sinanbir.com/web-api-simple-injector-dependcy-resolver/</link><guid isPermaLink="true">https://sinanbir.com/web-api-simple-injector-dependcy-resolver/</guid><pubDate>Wed, 23 Sep 2015 03:12:23 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>Merhaba arkada&scedil;lar&nbsp;bu makalemde Web Api servisimize bir IOC (Inversion Of Control ) framework'u olan Simple Injector implementasyonundan bahsetmek istiyorum. <a href="/2015/09/19/dependcy-injection-nedir-csharp/">Dependcy injection nedir makalemde</a>&nbsp;IOC &nbsp;prensibi uygulama y&ouml;ntemlerinden biri&nbsp;olan DI(Dependcy Injection)&nbsp;hakk&inodot;nda konu&scedil;mu&scedil;tuk. &nbsp;Bu makalemde ise Simple Injector framework'u ile bu dependcylerin birbirleri ile olan&nbsp;ba&gbreve;&inodot;ml&inodot;l&inodot;klar&inodot;n&inodot;n &ccedil;&ouml;z&uuml;lmesinden ve ya&scedil;am &ouml;m&uuml;rlerinden bahsetmek istiyorum.



Bo&scedil; bir Web Api uygulamas&inodot; olu&scedil;tural&inodot;m.Ben VS2015 kullan&inodot;yorum. Farkl&inodot; eki bir VS versiyonu kullan&inodot;yorsan&inodot;z direk Web Api template olarak se&ccedil;ip olu&scedil;turabilirsiniz.

<a href="/wp-content/uploads/2015/09/createproject.png"><img alt="createproject" class="alignnone size-full wp-image-43" decoding="async" height="633" loading="lazy" src="/wp-content/uploads/2015/09/createproject.png" width="818"></a>

Yeni projemizi olu&scedil;turduk sonra &nbsp;Simple Injector Web Api paketini&nbsp;kural&inodot;m. Kurulum i&ccedil;in nuget consol'a
</p><blockquote>Install-Package SimpleInjector.Integration.WebApi</blockquote><p>
komutunu yaz&inodot;p eklentiyi projemize dahil edelim. &Ouml;rnek olarak kullanaca&gbreve;&inodot;m&inodot;z dependcyleri olu&scedil;tural&inodot;m.

<a href="/wp-content/uploads/2015/09/dependicies.png"><img alt="dependicies" class="alignnone size-full wp-image-46" decoding="async" height="511" loading="lazy" src="/wp-content/uploads/2015/09/dependicies.png" width="419"></a>

Dependcies.cs dosyam&inodot;za a&scedil;a&gbreve;&inodot;daki kod blo&gbreve;unu ekleyelim.
</p><pre class="lang:c# decode:true" tabindex="0">public interface IUserDataRepository
        {
            List&lt;Data&gt; GetDatas();
        }

        public class SqlUserRepository : IUserDataRepository
        {
            public List&lt;Data&gt; GetDatas()
            {
                return new List&lt;Data&gt;()
                {
                    new Data() {Name = "Ali",Surname = "Devil",Age = 22},
                    new Data() {Name = "Veli",Surname = "Devil2",Age = 45},
                    new Data() {Name = "Hasan",Surname = "Devil3",Age = 36}
                };
            }
        }
        public class NoSqlUserRepository : IUserDataRepository
        {
            public List&lt;Data&gt; GetDatas()
            {
                return new List&lt;Data&gt;()
                {
                    new Data() {Name = "Elif",Surname = "Angel1",Age = 21},
                    new Data() {Name = "Nihal",Surname = "Angel2",Age = 75},
                    new Data() {Name = "Tu&gbreve;ba",Surname = "Angel3",Age = 45}
                };
            }
        }

        public class Data
        {
            public string Name  { get; set; }
            public string Surname { get; set; }
            public int Age { get; set; }
        }</pre><p>
&Scedil;imdi App_Start klasorunde yer alan&nbsp;WebApiConfig.cs dosyam&inodot;za ge&ccedil;elim ve Simple Injector&nbsp;ayarlar&inodot;n&inodot; yapal&inodot;m.
</p><pre class="lang:c# decode:true" tabindex="0" title="WebConfig">public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
            container.Register&lt;IUserDataRepository, SqlUserRepository&gt;(Lifestyle.Scoped);
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.Verify();
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }</pre><p>
&Scedil;imdi yeni bo&scedil; "user" ad&inodot;nda bir controller olu&scedil;tural&inodot;m.

<a href="/wp-content/uploads/2015/09/newcontroller.png"><img alt="newcontroller" class="alignnone size-full wp-image-52" decoding="async" height="664" loading="lazy" src="/wp-content/uploads/2015/09/newcontroller.png" width="952"></a>
</p><pre class="lang:c# decode:true" tabindex="0">public class UserController : ApiController
    {
        public IUserDataRepository UserDataRepository;

        public UserController(IUserDataRepository userDataRepository)
        {
            UserDataRepository = userDataRepository;
        }

        [HttpGet]
        public IEnumerable&lt;Data&gt; Get()
        {
            return UserDataRepository.GetDatas();
        }  
    }</pre><p>
Projemizi start edelim vede browserdan kendi localhost portunuza g&ouml;re istek yapal&inodot;m.

<a href="/wp-content/uploads/2015/09/sqloutput.png"><img alt="sqloutput" class="alignnone size-full wp-image-53" decoding="async" height="431" loading="lazy" src="/wp-content/uploads/2015/09/sqloutput.png" width="1179"></a>

vede g&ouml;rd&uuml;&gbreve;&uuml;n&uuml;z gibi veriler geldi.Injector bizim register etti&gbreve;imiz class&inodot;m&inodot;z&inodot; controller'a otomatik olarak ba&gbreve;lad&inodot;.Ornekte browser XML olarak istedi&gbreve;i i&ccedil;in veri XML geldi. Siz kendiniz ba&scedil;ka bir program kullanarak controller &uuml;zerinde &nbsp;hi&ccedil;bir de&gbreve;i&scedil;iklik yapmadan sadece iste&gbreve;in header&inodot;n&inodot; de&gbreve;i&scedil;tirerek JSON olarak veriyi alabilirsiniz.Web api bunu sizin i&ccedil;in yap&inodot;yor.

Dependcy register i&scedil;lemini uygulama ba&scedil;lang&inodot;c&inodot;nda yapt&inodot;k.Ornek olarak&nbsp;biz IUserDataRepository i&ccedil;in&nbsp;SqlUserRepository concrete class'&inodot;n&inodot; kullan&inodot;yoruz. Bunu&nbsp;NoSqlUserRepository olarak de&gbreve;i&scedil;tirdinizde verilerinde de&gbreve;i&scedil;ece&gbreve;ini g&ouml;receksiniz.

Burada bir di&gbreve;er &ouml;nemli konu ise &ouml;&gbreve;enin ya&scedil;am s&uuml;reci.Simple Injection i&ccedil;in 3 adet s&uuml;re&ccedil; mevcut. Bunlar Transient,Scoped,Singleton.Burada biz scoped kulland&inodot;k. Her istek i&ccedil;in bize servisin yeni bir &ouml;rne&gbreve;i geliyor.Bunu &ouml;rnek &uuml;zerinden anlat&inodot;rsak daha anla&scedil;&inodot;l&inodot;r olabilir. Bunun i&ccedil;in kod &uuml;zerinde baz&inodot; de&gbreve;i&scedil;iklikler yapal&inodot;m. A&scedil;a&gbreve;&inodot;da de&gbreve;i&scedil;iklik yap&inodot;lan kodlar&inodot; yeniden payla&scedil;&inodot;yorum
</p><pre class="lang:default decode:true" tabindex="0" title="WebApiConfig.cs">public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
            container.Register&lt;IUserDataRepository, SqlUserRepository&gt;(Lifestyle.Scoped);
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.Verify();
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }</pre>
<pre class="lang:c# decode:true" tabindex="0" title="Dependicies.cs Dosyas&inodot;">public interface IUserDataRepository
    {
        List&lt;Data&gt; GetDatas();
        void AddData(Data data);

    }

    public class SqlUserRepository : IUserDataRepository
    {
        public List&lt;Data&gt; List { get; set; }

        public SqlUserRepository()
        {
            List = new List&lt;Data&gt;()
                {
                    new Data() {Name = "Ali",Surname = "Devil",Age = 22},
                    new Data() {Name = "Veli",Surname = "Devil2",Age = 45},
                    new Data() {Name = "Hasan",Surname = "Devil3",Age = 36}
                };
        }
        public List&lt;Data&gt; GetDatas()
        {
            return List;
        }

        public void AddData(Data data)
        {
            List.Add(data);
        }
    }
    public class NoSqlUserRepository : IUserDataRepository
    {
        public List&lt;Data&gt; List { get; set; }

        public NoSqlUserRepository()
        {
            List = new List&lt;Data&gt;()
                {
                    new Data() {Name = "Elif",Surname = "Angel1",Age = 21},
                    new Data() {Name = "Nihal",Surname = "Angel2",Age = 75},
                    new Data() {Name = "Tu&gbreve;ba",Surname = "Angel3",Age = 45}
                };
        }
        public List&lt;Data&gt; GetDatas()
        {
            return List;
        }

        public void AddData(Data data)
        {
            List.Add(data);
        }
    }

    public class Data
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }</pre>
<pre class="lang:c# decode:true" tabindex="0" title="UserController">  public class UserController : ApiController
    {
        public IUserDataRepository UserDataRepository;

        public UserController(IUserDataRepository userDataRepository)
        {
            UserDataRepository = userDataRepository;
        }

        [HttpGet]
        public IEnumerable&lt;Data&gt; Get()
        {
            return UserDataRepository.GetDatas();
        }

        [HttpPost]
        public void AddData(Data data)
        {
            UserDataRepository.AddData(data);
        }
    }</pre><p>
G&ouml;rd&uuml;&gbreve;&uuml;n&uuml;z gibi sadece AddData fonksiyonunu ekledik&nbsp;ve config dosyas&inodot;nda route ayarlar&inodot;nda action parametresini ekledik.&nbsp;Bu de&gbreve;i&scedil;iklikleri yapt&inodot;ktan sonra projeyi &ccedil;al&inodot;&scedil;t&inodot;ral&inodot;m ve bir post i&scedil;lemi yapal&inodot;m. &Ouml;rnek Post &Ccedil;a&gbreve;r&inodot;s&inodot;:
</p><blockquote>POST http://localhost:62066/api/user/AddData HTTP/1.1
User-Agent: Fiddler
Host: localhost:62066
Content-Length: 42
Content-Type: application/json; charset=utf-8

{"Name":"Sinan","Surname":"Bir","Age":100}</blockquote><p>
Post i&scedil;leminden sonra normalde User controller'a get &ccedil;a&gbreve;r&inodot;s&inodot; yapt&inodot;&gbreve;&inodot;m&inodot;zda d&ouml;nen yan&inodot;tlar i&ccedil;inde &nbsp;{"Name":"Sinan","Surname":"Bir","Age":100} bu kay&inodot;d&inodot;n olmas&inodot; gerekiyor di mi ? Ama hay&inodot;r biz her istek yapt&inodot;&gbreve;&inodot;m&inodot;zda container bize servisin yeni bir &ouml;rne&gbreve;ini veriyor. Yani biz her seferinde ilk listeye eri&scedil;mi&scedil; oluyoruz. E&gbreve;er life scoped de&gbreve;ilde singleton olsayd&inodot; ne olurdu ? Bu sefer&nbsp;servisin sadece bir&nbsp;&ouml;rne&gbreve;ini container'&inodot;n life time'&inodot; boyunca bize verecekti. Biz farkl&inodot; istekler de yapsak i&scedil;lemlerin hepsi ayn&inodot; nesne &uuml;zerinde i&scedil;lem g&ouml;recekti. Ayn&inodot; &ccedil;a&gbreve;r&inodot;y&inodot; webconfig&nbsp;dosyas&inodot;ndaki iste&gbreve;i singleton olarak de&gbreve;i&scedil;tirip yapt&inodot;&gbreve;&inodot;m&inodot;zda&nbsp;kayd&inodot;n eklendi&gbreve;ini g&ouml;rebiliriz.

Simple injector kullanmam&inodot;n nedeni&nbsp;di&gbreve;er IOC frameworklere g&ouml;re biraz daha performansl&inodot; ve &ccedil;o&gbreve;u durumda i&scedil;imizi &ccedil;&ouml;z&uuml;yor.

Bugunluk bahsedeceklerim bunlar. Bir ba&scedil;ka makale ile g&ouml;r&uuml;&scedil;mek &uuml;zere. Ho&scedil;cakal&inodot;n.

&nbsp;</p>]]></content:encoded></item>
<item><title>.NET Fluent Validation ( Model Kontrolü )</title><link>https://sinanbir.com/net-fluent-api-validation-and-example-model-kontrolu/</link><guid isPermaLink="true">https://sinanbir.com/net-fluent-api-validation-and-example-model-kontrolu/</guid><pubDate>Sat, 19 Sep 2015 20:36:44 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p>Bu makalede&nbsp;.NET i&ccedil;in ek bir Nuget paket halinde bulunan Model kontrol i&ccedil;in geli&scedil;tirilmi&scedil; fluent interface ve lambda expression deste&gbreve;i olan g&uuml;zel bir eklentiden bahsetmek istiyorum. Daha &ouml;nce MVC yada herhangi benzeri Model Driven Architecture (MDA)&nbsp;prensibiyle uygulama geli&scedil;tirdiyseniz bu mimarilerde Model'lar i&ccedil;in validation ASP.NET core'u i&ccedil;erisinde yer alan Data Annotions &nbsp;ile yap&inodot;labilmekte. Fakat bu y&ouml;ntem ile validation yap&inodot;ld&inodot;&gbreve;&inodot; zaman&nbsp;model say&inodot;s&inodot; artt&inodot;&gbreve;&inodot;nda daha karma&scedil;&inodot;k ve y&ouml;netimi zor bir yap&inodot; olu&scedil;makta. Bunun yerine validation katman&inodot;n&inodot; business layer'a ta&scedil;&inodot;y&inodot;p tek bir yerden kontrol&uuml;n yap&inodot;lmas&inodot; ve model domain'in temiz kalmas&inodot;&nbsp;daha kontrol edilebilir bir yap&inodot; sa&gbreve;lamakta.

Data Annotions kullanmamaktan bahsetmiyorum, tercih meselesi. E&gbreve;er separation of concern prensibi &ccedil;er&ccedil;evesinde de&gbreve;erlendirecek olursak Domain katman&inodot;n&inodot; temiz b&inodot;rak&inodot;p validation'&inodot; ayr&inodot; bir katmanda kontrol etmek daha do&gbreve;ru olur.Amac&inodot;m programlama konsepti tart&inodot;&scedil;maktan &ccedil;ok paket ile &ouml;rnek uygulama yapmakt&inodot; merak etmeyin&nbsp;&ccedil;ok fazla uzatmadan hemen &ouml;rne&gbreve;e ge&ccedil;iyorum.

Fluent Api Validation y&uuml;klemek i&ccedil;in Nuget Console'a
</p><pre tabindex="0"><code>Install-Package FluentValidation</code></pre><p>
yazarak y&uuml;kleyebilirsiniz.

<strong>&Ouml;rnek ( Example)</strong>
</p><pre class="lang:c# decode:true" tabindex="0" title="Models">    public class Company
    {
        public string CompanyName { get; set; }
        public string EMail { get; set; }
        public string Phone { get; set; }
        public double AnnualIncome { get; set; }
        public string Address { get; set; }
        public List&lt;Employee&gt; Employees { get; set; }
    }

    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
    }</pre>
&nbsp;
<pre class="lang:c# decode:true" tabindex="0"> public class CompanyValidation : AbstractValidator&lt;Company&gt;
    {
        public CompanyValidation()
        {
            RuleFor(a =&gt; a.CompanyName).NotEmpty().Length(0, 8).WithMessage("You exceeded the maximum char limit");
                //Hatay&inodot; test etmek i&ccedil;in k&uuml;&ccedil;&uuml;k de&gbreve;er kullan&inodot;yorum
            RuleFor(a =&gt; a.Address).NotEmpty().Length(0, 250);
            RuleFor(a =&gt; a.EMail).EmailAddress().WithMessage("Invalid EMail");
            RuleFor(a =&gt; a.AnnualIncome).GreaterThan(0).LessThanOrEqualTo(5000000);
            RuleFor(a =&gt; a.Employees).SetCollectionValidator(new EmployeeValidation());
            //Collection i&ccedil;in normal validation bile kullanabiliyorsunuz
        } 
    }

    public class EmployeeValidation : AbstractValidator&lt;Employee&gt;
    {
        public EmployeeValidation()
        {
            RuleFor(e =&gt; e.Age).GreaterThan(18).LessThanOrEqualTo(150);
            RuleFor(e =&gt; e.Name).NotEmpty();
        }
    }</pre>
<pre class="lang:c# decode:true" tabindex="0" title="Program">        static void Main(string[] args)
        {
            var companyValidator = new CompanyValidation();
            var company = new Company();
            company.Employees= new List&lt;Employee&gt;();
           
            company.Employees.Add(new Employee());
            company.Employees.Add(new Employee() {Age = 255,Name = "Ali",Gender = "Male"});
            var validation = companyValidator.Validate(company);
            var errors = validation.Errors;
            var state = validation.IsValid;
            Console.WriteLine(state);
            foreach (var error in errors)
            {
                Console.WriteLine(error.PropertyName +"-"+ error);
            }
            Console.WriteLine("-----------------");
            Console.ReadLine();

        }</pre>
<p><strong>Program &Ccedil;&inodot;kt&inodot;s&inodot;</strong>
<a href="/wp-content/uploads/2015/09/validationresult.png"><img alt="validationresult" class="alignnone size-full wp-image-30" decoding="async" height="173" loading="lazy" src="/wp-content/uploads/2015/09/validationresult.png" width="542"></a>

G&ouml;rd&uuml;&gbreve;&uuml;n&uuml;z gibi model s&inodot;n&inodot;flar&inodot;m&inodot;z&inodot; temiz b&inodot;rakarak ( POCO &nbsp;s&inodot;n&inodot;flar ) validation sa&gbreve;lad&inodot;k.

Validation i&ccedil;in detayl&inodot; bilgi i&ccedil;in&nbsp;<a href="https://github.com/JeremySkinner/FluentValidation/wiki" rel="noopener" target="_blank">t&inodot;klay&inodot;n&inodot;z</a>

&nbsp;

Ba&scedil;ka bir makalede g&ouml;r&uuml;&scedil;mek &uuml;zere. Ho&scedil;&ccedil;akal&inodot;n.</p>]]></content:encoded></item>
<item><title>Dependcy Injection nedir ( C# ) Ornek? ( IOC )</title><link>https://sinanbir.com/dependcy-injection-nedir-csharp/</link><guid isPermaLink="true">https://sinanbir.com/dependcy-injection-nedir-csharp/</guid><pubDate>Sat, 19 Sep 2015 16:20:54 +0000</pubDate><dc:creator>deluxetiky</dc:creator><content:encoded><![CDATA[<p><strong>Dependcy Injection (DI) nedir&nbsp;? A&ccedil;&inodot;klama ve &Ouml;rnek uygulama.</strong>

Biz yaz&inodot;l&inodot;mc&inodot; arkada&scedil;lar&inodot;n genelde yaz&inodot;l&inodot;m geli&scedil;tirme denince olay&inodot;&nbsp;kodlama olarak d&uuml;&scedil;&uuml;n&uuml;p bir anda ba&scedil;lay&inodot;p sonunu getiremedi&gbreve;imiz bir &ccedil;ok proje olmu&scedil;tur. Tasar&inodot;m s&uuml;recine ayr&inodot;lan zaman&inodot;n kay&inodot;p oldu&gbreve;unu d&uuml;&scedil;&uuml;nmek yap&inodot;lan en b&uuml;y&uuml;k hatalardan sadece bir tanesi. Programda tasar&inodot;m s&uuml;recinin k&inodot;sa tutulmas&inodot;, isteklerin ne do&gbreve;rultuda gelece&gbreve;inin iyi de&gbreve;erlendirilmemesi sonucunda karma&scedil;&inodot;k yap&inodot;lar i&ccedil;erisine girmek, her istek i&ccedil;in kodun farkl&inodot; yerlerini de&gbreve;i&scedil;tirmek bu s&uuml;reci b&ouml;yle devam ettirirken&nbsp;projemizin do&gbreve;ru &ccedil;al&inodot;&scedil;t&inodot;&gbreve;&inodot;n&inodot; varsaymak ve devam etmek ilerde &ccedil;ok b&uuml;y&uuml;k sorunlara neden olmaktad&inodot;r.

<strong>Dependcy</strong> Injection hakk&inodot;nda konu&scedil;madan &ouml;nce hangi problemleri &ccedil;&ouml;zd&uuml;&gbreve;&uuml;n&uuml;&nbsp;konu&scedil;al&inodot;m,

 daha sonra &ouml;rnek bir uygulama ile bu prensibi anlatmaya &ccedil;al&inodot;&scedil;aca&gbreve;&inodot;m.Yukar&inodot;da bahsetti&gbreve;im sorunlarla y&uuml;zle&scedil;memek i&ccedil;in bahsedece&gbreve;im y&ouml;ntemlerden bir tanesi olan Dependcy Inversion (&nbsp;"<strong>SOLID</strong>" prensibinin sonuncusu ) program&inodot;m&inodot;z&inodot;n loosely coupled veya decoupled ( gev&scedil;ek ba&gbreve;l&inodot; ) olmas&inodot;n&inodot; sa&gbreve;lamaktad&inodot;r. Yani yaz&inodot;l&inodot;m i&ccedil;erisinde mod&uuml;llerin birbiri ile olan s&inodot;k&inodot; ba&gbreve;l&inodot;l&inodot;&gbreve;&inodot;n&inodot;n ortadan kald&inodot;r&inodot;lmas&inodot;n&inodot; sa&gbreve;lamaktad&inodot;r. Bu ba&gbreve;l&inodot;l&inodot;&gbreve;&inodot; ortadan kald&inodot;r&inodot;rken soyut katmanlar&inodot;&nbsp;kullanaca&gbreve;&inodot;z.Bu soyut katmanlar birbirine ba&gbreve;l&inodot; olan katmanlar&inodot;n ba&gbreve;l&inodot;l&inodot;&gbreve;&inodot;n&inodot; ortadan kald&inodot;r&inodot;rken bizim referans&inodot;m&inodot;z oluyor. Evet, &scedil;uana kadar anlatt&inodot;klar&inodot;m soyut gelebilir. &Ouml;rnek &uuml;zerinden anla&scedil;&inodot;lmas&inodot; daha kolay olacakt&inodot;r.

<strong>&Ouml;rnek Uygulama</strong>

&Ouml;rnek olarak, bir projede bilgilendirme mod&uuml;l&uuml; yazmak istiyorsunuz ve bilgilendirme i&ccedil;in sizden sadece mail olarak bilgilendirme istenmi&scedil; olsun. Klasik olarak bizim yapaca&gbreve;&inodot;m&inodot;z a&scedil;a&gbreve;&inodot;daki gibi bir kodlama olacakt&inodot;r. Uygulamay&inodot; &ouml;rnek bir c# console uygulamas&inodot; &uuml;zerinden anlataca&gbreve;&inodot;m
</p><pre class="lang:c# decode:true" tabindex="0">    public class Information
    {
        Email InformationSender { get; set; }
               
        public Information(Email email)
        {
            InformationSender = email;
        }
        public void SendInformation()
        {
            InformationSender.Send();
        }
    }

    public class Email
    {
        public void Send()
        {
            Console.WriteLine("Bildirim");
        }
    }</pre>
<pre class="lang:c# decode:true" tabindex="0" title="Program">static void Main(string[] args)
        {
            Information information = new Information(new Email());
            information.SendInformation();
            Console.ReadLine();
        }</pre><p>
Program &Ccedil;&inodot;kt&inodot;s&inodot; :

<a href="/wp-content/uploads/2015/09/result.png"><img alt="result" class="aligncenter wp-image-15 size-full" decoding="async" height="240" loading="lazy" src="/wp-content/uploads/2015/09/result.png" width="745"></a>

Yukar&inodot;daki kodu &ccedil;al&inodot;&scedil;t&inodot;rd&inodot;&gbreve;&inodot;m&inodot;zda program&inodot;m&inodot;z &ccedil;al&inodot;&scedil;acakt&inodot;r. Fakat burada olu&scedil;an problem Information s&inodot;n&inodot;f&inodot;m&inodot;z Email s&inodot;n&inodot;f&inodot;m&inodot;z ile ba&gbreve;l&inodot; yani Information s&inodot;n&inodot;f&inodot;n&inodot; Email s&inodot;n&inodot;f&inodot; olmadan kullanmak m&uuml;mk&uuml;n de&gbreve;il. Veya ilerde programa bir ba&scedil;ka bilgilendirme sistemi eklemek istedi&gbreve;imizde, &ouml;rne&gbreve;in sms bilgilendirmesi, Information s&inodot;n&inodot;f&inodot; &uuml;zerindeki kod bloklar&inodot;nda d&uuml;zenleme yapmak ka&ccedil;&inodot;n&inodot;lmaz olacakt&inodot;r. Email s&inodot;n&inodot;f&inodot;ndaki de&gbreve;i&scedil;iklikler do&gbreve;rudan Information s&inodot;n&inodot;f&inodot;n&inodot; etkilemekte. S&inodot;n&inodot;flar aras&inodot;ndaki bu derece s&inodot;k&inodot; ba&gbreve;l&inodot;l&inodot;klar kod d&uuml;zenlemesini zorla&scedil;t&inodot;rmakta ve b&uuml;y&uuml;k projelerde&nbsp;karma&scedil;&inodot;kl&inodot;&gbreve;a sebep olmakta. &Scedil;imdi &ouml;rnek bir kod blo&gbreve;u ile dependcy injection'&inodot; anlatmaya &ccedil;al&inodot;&scedil;aca&gbreve;&inodot;m. Injection y&ouml;ntemi olarak constructor injection kullanaca&gbreve;&inodot;m. Bunun d&inodot;&scedil;&inodot;nda siz isterseniz property injection da kullanabilirsiniz.
</p><pre class="lang:c# decode:true" tabindex="0" title="D&uuml;zenlemi&scedil; Kod">    public class Information
    {
        ISender InformationSender { get; set; }
               
        public Information(ISender informationSender)
        {
            InformationSender = informationSender;
        }
        public void SendInformation()
        {
            InformationSender.Send();
        }
    }

    public interface ISender
    {
        void Send();
    }

    public class Email : ISender
    {
        public void Send()
        {
            Console.WriteLine("Email Bildirim.");
        }
    }

    public class Sms : ISender
    {
        public void Send()
        {
            Console.WriteLine("Sms Bildirim.");
        }
    }</pre>
<pre class="lang:c# decode:true" tabindex="0" title="Program">        static void Main(string[] args)
        {
            Information mailInformation = new Information(new Email());
            mailInformation.SendInformation();
            Console.WriteLine("----------------------------");
            Information smsInformation = new Information(new Sms());
            smsInformation.SendInformation();
            Console.ReadLine();
        }</pre>
<p><a href="/wp-content/uploads/2015/09/result2.png"><img alt="result2" class="alignnone size-full wp-image-18" decoding="async" height="205" loading="lazy" src="/wp-content/uploads/2015/09/result2.png" width="617"></a>

G&ouml;rd&uuml;&gbreve;&uuml;n&uuml;z gibi art&inodot;k information s&inodot;n&inodot;f&inodot;m&inodot;z&inodot;n di&gbreve;er hi&ccedil;bir alt s&inodot;n&inodot;f ile do&gbreve;rudan ba&gbreve;&inodot;ml&inodot;l&inodot;&gbreve;&inodot; kalmad&inodot;. Information s&inodot;n&inodot;f&inodot; i&ccedil;in tek ba&gbreve;&inodot;ml&inodot;l&inodot;k ISender inteface'i. Information s&inodot;n&inodot;f&inodot;nda ISender interface'ini implemente eden y&uuml;zlerce farkl&inodot;&nbsp;concrete s&inodot;n&inodot;f&inodot; kullabiliriz. Projede isteklerin hi&ccedil;bir zaman sabit kalmamas&inodot; , geni&scedil;lemelerin &ccedil;ok olmas&inodot;n&inodot; g&ouml;z &ouml;n&uuml;ne alarak Dependcy Injection'&inodot;n &ouml;nemimin ne derece fazla oldu&gbreve;unu g&ouml;stermekte.

Blogumda ilk makale olmas&inodot;da benim i&ccedil;in ayr&inodot; heycan verici.

Bir ba&scedil;ka makale ile beraber olmak &uuml;zere ho&scedil;&ccedil;akal&inodot;n.

&nbsp;

&nbsp;

&nbsp;</p>]]></content:encoded></item>
</channel>
</rss>
